Java How to Program 2 e Deitel Deitel

  • Slides: 19
Download presentation
Java How to Program, 2 e Deitel & Deitel Chapter 13 Multithreading Slides by

Java How to Program, 2 e Deitel & Deitel Chapter 13 Multithreading Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus 1

Chapter 13 Topics l l Class Thread and Thread methods Thread States: Life Cycle

Chapter 13 Topics l l Class Thread and Thread methods Thread States: Life Cycle of a Thread Synchronization Runnable Interface 2

How do you eat breakfast? l Do you eat all your cereal, followed by

How do you eat breakfast? l Do you eat all your cereal, followed by all your toast, followed by all your coffee? SINGLE-THREADING l Or, do you eat a few spoonfuls of cereal and then a bite of toast and then a sip of coffee, and so on? MULTI-THREADING 3

Concurrent programming l When several tasks are done at one time we say they

Concurrent programming l When several tasks are done at one time we say they are done concurrently. l In Java, concurrent programming is handled by threads. l This is called multitasking, and requires the use of a separate thread for each task. 4

Time slicing l Even though the CPU executes one statement at a time, it

Time slicing l Even though the CPU executes one statement at a time, it can run multiple threads concurrently by rapidly alternating among them. How it does this is called scheduling. l Time slicing is a scheduling technique used in Win 32 implementations of Java. l Each thread is given a limited amount of time to execute, and when that time expires the thread must wait while other threads get their chances to use their time in round-robin fashion. 5

Inheritance Hierarchy Object superclass Thread subclass 6

Inheritance Hierarchy Object superclass Thread subclass 6

java. lang. Thread class public class Thread extends Object implements Runnable { // Default

java. lang. Thread class public class Thread extends Object implements Runnable { // Default Constructor public Thread( ); // Constructor with Runnable object supplied public Thread( Runnable target ); // Constructor with String supplied public Thread( String thread. Name ); 7

java. lang. Thread class // Class Methods // Argument ms specifies how long the

java. lang. Thread class // Class Methods // Argument ms specifies how long the currrently // executing thread should sleep in milliseconds. // Meanwhile other threads can execute. public static native void sleep( long ms ) throws Interrupted. Exception; // A call to yield gives other threads of equal priority // a chance to execute on non-timesliced systems. public static native void yield( ); 8

java. lang. Thread class // Instance Methods public final String get. Name( ); public

java. lang. Thread class // Instance Methods public final String get. Name( ); public final int get. Priority( ); public void run( ); public final void set. Name( ); public final void set. Priority( ); public synchronized native void start( ); public final void stop( ); 9

Instance Method start public synchronized native void start( ); // Is used to launch

Instance Method start public synchronized native void start( ); // Is used to launch a thread’s execution. // Calls method run and immediately returns to its caller. // The caller executes concurrently with launched thread. 10

Life Cycle of a Thread notify() notify. All() Done sleeping Sleeping start() I/O done

Life Cycle of a Thread notify() notify. All() Done sleeping Sleeping start() I/O done Ready yield() Dispatch sleep() Running I/O requested wait() Waiting stop() Blocked Dead 11

Thread State Java Description Ready The thread is ready to run and waiting for

Thread State Java Description Ready The thread is ready to run and waiting for the CPU Running The thread is executing on the CPU Waiting The thread is waiting for some event to happen Sleeping The thread has been told to sleep for some time Blocked The thread is waiting for I/O to finish Dead The thread is terminated 12

2 Ways to Create a Java Thread USEFUL WHEN YOU ALREADY HAVE A CLASS

2 Ways to Create a Java Thread USEFUL WHEN YOU ALREADY HAVE A CLASS THAT YOU WANT TO CREATE A THREAD FROM Define a subclass of Thread Have the class implement the Runnable interface. Override the default method run( ) You must define method run( ) Pass a runnable object of your class to a new Thread instance 13

Creating a Thread l One way to create a thread in Java is to

Creating a Thread l One way to create a thread in Java is to define a subclass of Thread and overriding the default run() method. l Another way to create a thread in Java is to pass a Runnable object to a new Thread instance. The object’s run() method is invoked automatically as soon as the thread’s start() method is called. 14

Morelli’s Fly subclass definition import java. awt. *; // Import GUI components public class

Morelli’s Fly subclass definition import java. awt. *; // Import GUI components public class Fly extends Cyber. Pet implements Runnable { // We want the fly to buzz around in rectangular area // just outside the spider's web. private private static static final final int int int XMIN XMAX YMIN YMAX SIDE = = = 225; 300; 245; 305; 5; // Size of fly private static final int MAX_RANGE = 15; // Max and min change of location private static final int MIN_DELTA = -10; private Cyber. Pet. Applet applet; private Point location; // Simulation interface // Coordinates of fly in applet 15

Morelli’s Fly subclass definition public Fly (Cyber. Pet. Applet app) { applet = app;

Morelli’s Fly subclass definition public Fly (Cyber. Pet. Applet app) { applet = app; location = new Point(XMAX, YMAX); // Starting location state = FLYING; } public Point get. Location() { return location; } 16

public synchronized void buzzaround() { state = FLYING; Graphics g = applet. get. Graphics();

public synchronized void buzzaround() { state = FLYING; Graphics g = applet. get. Graphics(); // Erase current image g. set. Color(Color. white); g. fill. Rect(location. x, location. y, SIDE); // Calculate new location int dx = (int)(MIN_DELTA + Math. random()* MAX_RANGE); int dy = (int)(MIN_DELTA + Math. random()* MAX_RANGE); if (location. x + dx >= XMIN) else location. x += dx; location. x = XMIN; if (location. y + dy >= YMIN) else location. y += dy; location. y = YMIN; if (location. x + dx <= XMAX) else location. x += dx; location. x = XMAX; if (location. y + dy <= YMAX) else location. y += dy; location. y = YMAX; 17

// Draw new image at new location g. set. Color(Color. red); g. fill. Rect(location.

// Draw new image at new location g. set. Color(Color. red); g. fill. Rect(location. x, location. y, SIDE); } // buzzaround() public synchronized void die() state = DEAD; } public void run() { while (state != DEAD) { buzzaround(); delay(125); }//while } // run() } // Fly 18

ACKNOWLEDGMENT: 19

ACKNOWLEDGMENT: 19