|
|
Threads - Thread mechanics
Wait Sets (CPJ pg 184)
- just as every object has a lock it also has a wait set that is manipulated using wait(), notify(), notifyAll() and Thread.interrupt
- objects having locks and wait sets are referred to as monitors
- any object can act as a monitor
- each object's wait set is maintained internally by the JVM and holds threads blocked by wait until a corresponding notify is received or the waits are otherwise released
- the methods wait(), notify() and notifyAll() can only be invoked when the synchronized lock is held on their target
wait()
notify()
the following happens when notify() is invoked
- the JVM arbitrarily chooses a thread, if one exists, from the target's wait set
- the thread must re-obtain it's synchronized lock on the target object. It will always be blocked at least until the thread calling notify() releases it's lock or if some other thread obtains the lock first
- once the lock is obtained, the thread resumes from the point of it's wait
notifyAll()
- works the same as notify() except all waiting threads are removed from the target wait set and allowed to compete for the lock
- only one thread can obtain the lock so they continue one at a time
Thread.interrupt
- if a thread suspended in wait is invoked, the same notify mechanics apply except that after re-acquiring the lock, an InterruptedException is thrown
- if an interrupt and notify occur together there is NO guarantee as to which will take precedence
Example Code
- Using wait() and notify() to control access to a shared resource
Thread5
|