Java How to Program, Second Edition - CCBC Faculty Web

cavalcadejewelΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 11 μήνες)

95 εμφανίσεις

1

Java

How to Program, 2e


Deitel & Deitel

Chapter 13

Multithreading




Slides by Sylvia Sorkin, Community College of Baltimore County
-

Essex Campus

2

Chapter 13 Topics


Class Thread and Thread methods


Thread States: Life Cycle of a Thread


Thread Synchronization


Runnable Interface

3

How do you eat breakfast?



Do you eat all your cereal, followed by all
your toast, followed by all your coffee?


SINGLE
-
THREADING



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


4

Concurrent programming



When
several tasks are done at one time

we say they are done concurrently.



In Java, concurrent programming is
handled by threads.



This is called
multitasking
, and requires
the use of a separate thread for each
task.

5

Time slicing


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.



Time slicing is a scheduling technique

used in
Win32 implementations of Java.




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.


6

Inheritance Hierarchy

Object

Thread

superclass

subclass

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 threadName );



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 InterruptedException;





// A call to yield gives other threads of equal priority


// a chance to execute on non
-
timesliced systems.



public static native void yield( );





java.lang.Thread

class


// Instance Methods



public final String getName( );


public final int getPriority( );


public void run( );


public final void setName( );


public final void setPriority( );


public synchronized native void start( );


public final void stop( );






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.




Instance Method
start

11

Life Cycle of a Thread


notify()


notifyAll()


start()

I/O done

Waiting

Running

Ready

Sleeping

Blocked

Dead

sleep()

wait()

stop()

yield()

I/O requested


Done

sleeping

Dispatch

12

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

13

2 Ways to Create a Java Thread


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

USEFUL WHEN YOU ALREADY

HAVE A CLASS THAT YOU WANT

TO CREATE A THREAD FROM

14

Creating a
Thread



One way to create a thread in Java is to define a
subclass of
Thread
and overriding the default
run()

method.



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.

Morelli’s
Fly

subclass definition

import java.awt.*; // Import GUI components


public class Fly extends CyberPet





implements Runnable {



// We want the fly to buzz around in rectangular area


// just outside the spider's web.



private static final int XMIN = 225;


private static final int XMAX = 300;


private static final int YMIN = 245;


private static final int YMAX = 305;


private static final int SIDE = 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 CyberPetApplet applet;
// Simulation interface



private Point location;
// Coordinates of fly in applet


Morelli’s
Fly

subclass definition



public Fly (CyberPetApplet app) {


applet = app;


location = new Point(XMAX, YMAX);






// Starting location


state = FLYING;


}




public Point getLocation() {


return location;


}





public synchronized void buzzaround() {



state = FLYING;


Graphics g = applet.getGraphics();






// Erase current image


g.setColor(Color.white);


g.fillRect(location.x, location.y, SIDE, 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)

location.x += dx;


else





location.x = XMIN;



if (location.y + dy >= YMIN) location.y += dy;


else





location.y = YMIN;



if (location.x + dx <= XMAX)

location.x += dx;


else




location.x = XMAX;



if (location.y + dy <= YMAX)

location.y += dy;


else




location.y = YMAX;


// Draw new image at new location



g.setColor(Color.red);


g.fillRect(location.x, location.y, SIDE, SIDE);


} // buzzaround()



public synchronized void die()


state = DEAD;


}



public void run() {


while (state != DEAD) {


buzzaround();


delay(125);


}//while


} // run()

} // Fly


19

ACKNOWLEDGMENT:

This project was supported in part
by a grant from the National
Science Foundation under grant
No. DUE-ATE 9950056.