Java Reference
In-Depth Information
package com.oozinoz.machine;
import java.util.*;
public class BinStack
{
public static final int STACK_LIMIT = 3;
private Stack stack = new Stack();
synchronized public Bin pop()
{
while (stack.size() == 0)
{
try
{
wait();
Thread.sleep(500);
}
catch (InterruptedException ignore)
{
}
}
if (stack.size() == STACK_LIMIT)
{
notify();
}
return (Bin) stack.pop();
}
synchronized public void push(Bin b)
{
/* ? */
}
public int size()
{
return stack.size();
}
}
If the stack is empty, the
pop()
method causes the thread that called it to wait. This thread
will wait until the
push()
method—which you are about to write—awakens it. When the
pop()
method wakes up after waiting, it waits another half second. This lets a newly stacked
bin briefly appear in the GUI before this method snatches it away. The
pop()
method checks
the size of the stack in a
while
loop in case other threads might pop the stack, although this
won't occur in the
ShowWaitAndNotify
application.
When the stack is nonempty, the
pop()
method checks to see whether the stack is full. If the
stack is full, another thread may be waiting to push another bin, so the
pop()
method calls
notify()
. This will cause any thread waiting on the
BinStack
object's monitor to wake up
when
pop()
completes. The
pop()
method concludes by popping the top
Bin
object.
CHALLENGE 26.1
Write the code for the
push()
method of the
BinStack
class.