Java Reference
In-Depth Information
Figure 8.5
(a) The
Filler
and
Getter
threads need to access the bin in the
Box
.
The
Getter
needs, however, to wait till the bin is filled. (b) While the
Filler
places a
value in the bin via the synchronized
put()
method, the
Getter
cannot invoke the
synchronized
get()
method. (c) Similarly, the
Filler
must wait till the
Getter
finishes invoking the
get()
method before it can invoke
put()
.
In the following code for the
Box
class, we see that the
get()
and
put()
methods are prefaced by the modifier
synchronized
. This indicates that only
one thread can invoke either of these methods at the same time for the same object.
That is, during the time that a thread executes, say, the
get()
method, no other
thread can execute either the
get()
or
put()
method for the same
Box
object.
public class
Box
{
private int fBin;
private boolean fFilled = false;
Outputable fOutput;
/** Constructor obtains reference to Outputable object.
**/
Box (Outputable out) {
fOutput = out;
Search WWH ::
Custom Search