Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Never Ends.

Slides:



Advertisements
Similar presentations
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Advertisements

Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
GUI and Swing, part 2 The illustrated edition. Scroll bars As we have previously seen, a JTextArea has a fixed size, but the amount of text that can be.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Slides prepared by Rose Williams, Binghamton University Mouse Events + Chapter 17: Applets.
Java Threads Part I. Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications in.
Java Threads Part II. Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Threads Part I.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Threads Part II.
Public class MyThread1 extends Thread { public void start() { } public void run() { System.out.print(“Hello \n”) } public class MyThread2 extends Thread.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Unit 151 Threads II Thread Priorities The interrupt() method Threads Synchronization Thread Animation Examples – after each section Exercises.
Slides prepared by Rose Williams, Binghamton University Chapter 19 Swing II.
Slides prepared by Rose Williams, Binghamton University Chapter 18 Applets.
1 Applets Chapter 1 To understand:  why applets are used to extend the capabilities of Web pages  how an applet is executed and know about the restrictions.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Java Threads Part II. Lecture Objectives To understand the concepts of multithreading in Java To be able to develop simple multithreaded applications.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
Slides prepared by Rose Williams, Binghamton University ICS201 Lectures 18 : Threads King Fahd University of Petroleum & Minerals College of Computer Science.
Chapter 19 Java Never Ends Slides prepared by Rose Williams, Binghamton University Kenrick Mock University of Alaska Anchorage Copyright © 2008 Pearson.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Java: Animation Chris North cs3724: HCI. Animation? Changing graphics over time Examples: cartoons Clippy, agents/assistants Hour glass Save dohicky Progress.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
CS12420 – Swing and threads Lynda Thomas
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Week 3, Day 1: Processes & Threads Processes Threads SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Web Based Programming Section 8 James King 12 August 2003.
J McQuillan SE204: 2004/2005: Lecture 4slide 1 The Graphics Class Used when we need to draw to the screen Two graphics classes –Graphics –Graphics2D.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 13 : Swing I King Fahd University of Petroleum & Minerals College of Computer Science.
CMSC 202 Swing. Fall Introduction to Swing Swing is a Java package used to create GUIs The Java AWT (Abstract Window Toolkit) package is the original.
Field Trip #19 Animations with Java By Keith Lynn.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Chapter 5: Ball Worlds Features 2 classes, constant data fields, constructors, extension through inheritance, graphics.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Review of Graphics in Java,
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Concurrent Programming and Threads Threads Blocking a User Interface.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Never Ends.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Slides prepared by Rose Williams, Binghamton University Chapter 19 Swing II.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Java Applets Adding Animation. Import Files You still need to include the same files: –import java.applet.*; –import java.awt.*;
Programming and Problem Solving With Java Copyright 1999, James M. Slack Threads and Animation Threads Animation.
Chapter 11: Threaded Programs Situations where the program is following multiple execution paths (how to stop one?) Thread: a line of execution Thread.
Block 1 Unit 2 Basic Constructs in Java. Objectives create a simple object using a constructor; create and display a window frame on your computer screen;
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
Multithreaded applets
Chapter 19 Java Never Ends
9. Threads SE2811 Software Component Design
Threads.
9. Threads SE2811 Software Component Design
9. Threads SE2811 Software Component Design
Presentation transcript:

Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Never Ends

© 2006 Pearson Addison-Wesley. All rights reserved20-2 Reading Assignment: 19.1

© 2006 Pearson Addison-Wesley. All rights reserved20-3 Multithreading In Java, programs can have multiple threads –A thread is a separate computation process Threads are often thought of as computations that run in parallel –Although they usually do not really execute in parallel –Instead, the computer switches resources between threads so that each one does a little bit of computing in turn Modern operating systems allow more than one program to run at the same time –An operating system uses threads to do this

© 2006 Pearson Addison-Wesley. All rights reserved20-4 Thread.sleep Thread.sleep is a static method in the class Thread that pauses the thread that includes the invocation –It pauses for the number of milliseconds given as an argument –Note that it may be invoked in an ordinary program to insert a pause in the single thread of that program It may throw a checked exception, InterruptedException, which must be caught or declared –Both the Thread and InterruptedException classes are in the package java.lang

© 2006 Pearson Addison-Wesley. All rights reserved20-5 The getGraphics Method The method getGraphics is an accessor method that returns the associated Graphics object of its calling object –Every JComponent has an associated Graphics object Component.getGraphics();

© 2006 Pearson Addison-Wesley. All rights reserved20-6 A Nonresponsive GUI The following program contains a simple GUI that draws circles one after the other when the "Start" button is clicked –There is a 1/10 of a second pause between drawing each circle If the close-window button is clicked, nothing happens until the program is finished drawing all its circles Note the use of the Thread.sleep (in the method doNothing ) and getGraphics (in the method fill ) methods

© 2006 Pearson Addison-Wesley. All rights reserved20-7 Nonresponsive GUI (Part 1 of 9)

© 2006 Pearson Addison-Wesley. All rights reserved20-8 Nonresponsive GUI (Part 2 of 9)

© 2006 Pearson Addison-Wesley. All rights reserved20-9 Nonresponsive GUI (Part 3 of 9)

© 2006 Pearson Addison-Wesley. All rights reserved20-10 Nonresponsive GUI (Part 4 of 9)

© 2006 Pearson Addison-Wesley. All rights reserved20-11 Nonresponsive GUI (Part 5 of 9)

© 2006 Pearson Addison-Wesley. All rights reserved20-12 Nonresponsive GUI (Part 6 of 9)

© 2006 Pearson Addison-Wesley. All rights reserved20-13 Nonresponsive GUI (Part 7 of 9)

© 2006 Pearson Addison-Wesley. All rights reserved20-14 Nonresponsive GUI (Part 8 of 9)

© 2006 Pearson Addison-Wesley. All rights reserved20-15 Nonresponsive GUI (Part 9 of 9)

© 2006 Pearson Addison-Wesley. All rights reserved20-16 Fixing a Nonresponsive Program Using Threads This is why the close-window button does not respond immediately: –Because the method fill is invoked in the body of the method actionPerformed, the method actionPerformed does not end until after the method fill ends –Therefore, the method actionPerformed does not end until after the method fill ends –Until the method actionPerformed ends, the GUI cannot respond to anything else

© 2006 Pearson Addison-Wesley. All rights reserved20-17 Fixing a Nonresponsive Program Using Threads This is how to fix the problem: –Have the actionPerformed method create a new (independent) thread to draw the circles –Once created, the new thread will be an independent process that proceeds on its own –Now, the work of the actionPerformed method is ended, and the main thread (containing actionPerformed ) is ready to respond to something else –If the close-window button is clicked while the new thread draws the circles, then the program will end

© 2006 Pearson Addison-Wesley. All rights reserved20-18 The Class Thread In Java, a thread is an object of the class Thread Usually, a derived class of Thread is used to program a thread –The methods run and start are inherited from Thread –The derived class overrides the method run to program the thread –The method start initiates the thread processing and invokes the run method

© 2006 Pearson Addison-Wesley. All rights reserved20-19 A Multithreaded Program that Fixes a Nonresponsive GUI The following program uses a main thread and a second thread to fix the nonresponsive GUI –It creates an inner class Packer that is a derived class of Thread –The method run is defined in the same way as the previous method fill –Instead of invoking fill, the actionPerformed method now creates an instance of Packer, a new independent thread named packerThread –The packerThread object then invokes its start method –The start method initiates processing and invokes run

© 2006 Pearson Addison-Wesley. All rights reserved20-20 Threaded Version of FillDemo (Part 1 of 6)

© 2006 Pearson Addison-Wesley. All rights reserved20-21 Threaded Version of FillDemo (Part 2 of 6)

© 2006 Pearson Addison-Wesley. All rights reserved20-22 Threaded Version of FillDemo (Part 3 of 6)

© 2006 Pearson Addison-Wesley. All rights reserved20-23 Threaded Version of FillDemo (Part 4 of 6)

© 2006 Pearson Addison-Wesley. All rights reserved20-24 Threaded Version of FillDemo (Part 5 of 6)

© 2006 Pearson Addison-Wesley. All rights reserved20-25 Threaded Version of FillDemo (Part 6 of 6)

© 2006 Pearson Addison-Wesley. All rights reserved20-26 The Runnable Interface Another way to create a thread is to have a class implement the Runnable interface –The Runnable interface has one method heading: public void run(); A class that implements Runnable must still be run from an instance of Thread –This is usually done by passing the Runnable object as an argument to the thread constructor

© 2006 Pearson Addison-Wesley. All rights reserved20-27 The Runnable Interface: Suggested Implementation Outline public class ClassToRun extends SomeClass implements Runnable {... public void run() { // Fill this as if ClassToRun // were derived from Thread }... public void startThread() { Thread theThread = new Thread(this); theThread.start(); }... }

© 2006 Pearson Addison-Wesley. All rights reserved20-28 The Runnable Interface (Part 1 of 5)

© 2006 Pearson Addison-Wesley. All rights reserved20-29 The Runnable Interface (Part 2 of 5)

© 2006 Pearson Addison-Wesley. All rights reserved20-30 The Runnable Interface (Part 3 of 5)

© 2006 Pearson Addison-Wesley. All rights reserved20-31 The Runnable Interface (Part 4 of 5)

© 2006 Pearson Addison-Wesley. All rights reserved20-32 The Runnable Interface (Part 5 of 5)

© 2006 Pearson Addison-Wesley. All rights reserved import javax.swing.*; 2.public class TimeThread extends JFrame implements Runnable { private JTextField sec, min, hrs; 5. private JPanel panel; 6. private int time = 0; public TimeThread() { 9. super(“Time"); sec = new JTextField(3); sec.setEditable(false); //makes textfield uneditable 12. min = new JTextField(3); min.setEditable(false); 13. hrs = new JTextField(3); hrs.setEditable(false); panel = new JPanel(); panel.add(hrs); panel.add(min); panel.add(sec); getContentPane().add(panel); pack(); setVisible(true); 20. } Example 4

© 2006 Pearson Addison-Wesley. All rights reserved public void run() 2. { 3. try { 4. while(true) { 5. Thread.sleep(1000); time++; 6. sec.setText(time%60 + ""); //Display seconds 7. min.setText((time – (time/3600)*3600)/60 + ""); //Display minutes 8. hrs.setText(time/ ""); //Display hours 9. } 10. } catch(InterruptedException e) {} 11. } 12. public static void main(String[] args) 13. { 14. TimeThread t = new TimeThread(); 15. Thread mytime = new Thread(t); 16. mytime.start(); 17. } 18.} Example 4- Continued

© 2006 Pearson Addison-Wesley. All rights reserved20-35 Threads For Animation Threads can also be used to create animations. In the next example we show a program where a thread is used to create an animation of a ball moving vertically. The run() method increments the y coordinate of the ball to be drawn. If the y-coordinate exceeds the height of the window, the ball is reflected back by negating the increment. The complete program appears in the next slide.

© 2006 Pearson Addison-Wesley. All rights reserved20-36 Example 5 – Thread Animations import java.awt.*; import javax.swing.*; public class UpDown extends JFrame { public UpDown () { setSize(400,500); add(new DrawingArea()); } class DrawingArea extends JPanel implements Runnable { int radius, xc, yc; Thread t; public DrawingArea() { radius = 20; xc = 30; //signifies x location yc = 20; //signifies y location Thread t = new Thread (this); t.start(); }

© 2006 Pearson Addison-Wesley. All rights reserved20-37 public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.blue); g.fillOval(xc - radius, yc - radius, 2*radius, 2*radius); } public void run(){ int incry=10; int sleepFor = 50; while(true) { yc += incry ; repaint(); if(yc - radius getSize().height) incry = -incry; //reflect the ball back try{ Thread.sleep (sleepFor); }catch(InterruptedException e) {} } // end while } } public static void main(String[] args){ new UpDown().setVisible(true); }} Example 5 – continued