Professional Documents
Culture Documents
The Life Cycle of A Thread: Running
The Life Cycle of A Thread: Running
running
run() terminates
Dead
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
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).
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.