Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 11

The Life Cycle of a Thread

running

start() New Thread Runnable Not Runnable

run() terminates

Dead

In and Out of Runnable


Out of Runnable sleep() is invoked. wait() is invoked (for a specified condition to be satisfied). Thread is blocked on I/O. Back to Runnable Specified number of milliseconds elapsed. An object notifies the waiting thread that the condition is satisfied. I/O event the thread is blocked on, is completed.

sleep

new

start

Done sleepin g

blocked

suspend

resume
notify

wait

runnable
Block on I/O I/O complete stop

dead
Thread States from Core Java. Drawn by Ping Wu

Alive( ) and join( )


Two ways exist to determine whether a thread has finished.
final boolean isAlive( ) final void join( ) throws InterruptedException.

join( ) allow you to specify a maximum amount of time that want to wait for the specified thread to terminate.

Thread Priorities
final void setPriority(int level)
Level range MIN_PRIORITY and MAX_PRIORITY. These values are 1 and 10, respectively. default priority NORM_PRIORITY, which is currently 5.
final int getPriority( )

Synchronization
Two or more threads need access to a shared resource, some way to ensure that the resource will be used by only one thread at a time. The process is called synchronization. synchronization is the concept of the monitor (also called a semaphore).

synchronized(object) { // statements to be synchronized }

Interthread Communication
Threads also provide a benefit:
they do away with polling. Polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time. To avoid polling: wait( ), notify( ), and notifyAll( ) methods

final void wait( ) throws InterruptedException final void notify( ) final void notifyAll( ) EG: Producer, and Consumer.

Deadlock
Two threads have a circular dependency on a pair of synchronized objects. Deadlock is a difficult error to debug for two reasons:
In general, it occurs only rarely, when the two threads time-slice in just the right way. It may involve more than two threads and two synchronized objects.

Suspending, Resuming, and Stopping Threads


final void suspend( ) final void resume( ) stop( ) method The resume( ) method is also deprecated. It does not cause problems, but cannot be used without the suspend( ) method as its counterpart.

You might also like