An example portraying wait( ) and
notify( ) thread interaction
Peter Komisar
Most texts have a verbose explanation of the Producer Consumer model. My attempt to produce an alternative resulted in something longer than anything I've seen in any text books. If you have the time. . . |
Circumstances may exist where a thread seeks and gains the cpu to check
a condition. The condition
hasn't changed so cpu time was wasted in the process.Carry this thought
into an analogy of a citizen
checking the post office for the arrival of a parcel. But rather than
having time wasted with unsuccessful
checks, the postman suggests the customer wait and be notified when
the parcel arrives. In this analogy,
the post office is the object where threads (people) are queued (synchronized)
for service. (Only one
person has the postman's attention at one time). When the postman (the
cpu) checks for your parcel, he
see's if it is in. (The act of 'checking' is the role of a synchronized
method. Whether the parcel is in or
not describes a boolean condition used to tell the thread to wait or
to be notified, in the analogy,
whether the person should come back to the post office.) The person
waiting is analogous to a thread
being blocked.
The object being used to synchronize 'keeps' it's threads in a 'waiting
pool'. When the condition changes
(i.e.the parcel arrives and boolean is switched to true) the object
can notify the waiting threads to return
to the ready state to contend for the cpu. Note if all the threads
in the waiting pool are waiting for the same
condition to change, (return to the analogy, the tax refunds are in)
the object can notifyAll( ) threads to
return to the ready state.
The producing side of the equation can also participate in this
analogy. Mail delivery vehicles arriving at
the post office can participate in 'calling' (methods) from the post
office to dispatch the notification that the
wait for a parcel can be discontinued. Meanwhile other operations at
the post office (representing static
synchronized methods and non-synchronized methods) would carry on independently,
business as usual.