Java Reference
In-Depth Information
You may have noticed that the
pop()
method of
BinStack
calls
notify()
before it pops
an object from the stack. If a waiting thread were to wake up and start accessing the stack
before this method pops an object, the stack would overflow.
CHALLENGE 26.2
There is, in fact, no danger in the
BinStack
code that a thread waiting to push an
object will start executing before the
pop()
method completes its pop. Why is that?
The
Object
class comments provide a surprising amount of documentation on how
wait()
and
notify()
work. Another excellent reference on these methods is
The Java™ Class
Libraries, Volume 1
(Chan, Lee, and Kramer 1998). For an extensive work on many
applications of Java's locking facilities, I also recommend
Concurrent Programming in
Java™
(Lea 2000).
To use a
BinStack
object, create a thread that pushes or pops an object to the stack.
The
actionPerformed()
method of
ShowWaitAndNotify
provides an example:
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source.equals(loadButton()))
{
new Thread()
{
public void run()
{
loadButton().setEnabled(false);
binStack().push(new Bin("a bin"));
loadButton().setEnabled(true);
stackPanel().repaint();
}
}
.start();
}
if (source.equals(unloadButton()))
{
new Thread()
{
public void run()
{
unloadButton().setEnabled(false);
binStack().pop();
unloadButton().setEnabled(true);
stackPanel().repaint();
}
}
.start();
}
}