Java Reference
In-Depth Information
The
wait
method releases the object's lock before transitioning into the
WAITING
or
TIMED_WAITING
state.
If the
wait
method does not release the lock, no other thread can invoke
notify
because
the
notify
method requires the lock.
The
wait
and
notify
methods are used in a producer/consumer model where one
thread is “producing” something and another thread is “consuming” something. If the
producer is too fast, it might need to wait for the consumer. Once the consumer catches up,
it can notify the producer to start producing again.
To demonstrate a producer and consumer model, let's use the thread-safe
MyStack2
class
from the previous section. The class contains two fi elds:
public class MyStack2 {
private int [] values = new int[10];
private int index = 0;
//remainder of class definition
}
Suppose a thread (our producer) pushes values onto the stack, and another thread (our
consumer) pops values off the stack. If the stack is empty, the popping thread can wait for
the pushing thread to push something onto the stack. Once a push occurs, the pushing
thread can notify the popping thread to resume execution.
Let's start with the consumer thread. The following class named
Consumer
tries to pop
values off of a
MyStack2
object. Study the code and see if you can determine what it does:
1. public class Consumer extends Thread {
2. private MyStack2 stack;
3.
4. public Consumer(MyStack2 stack) {
5. this.stack = stack;
6. }
7.
8. public void run() {
9. while(true) {
10. synchronized(stack) {
11. int x = stack.pop();
12. if(x == -1) {
13. try {
14. System.out.println(“Waiting...”);
15. stack.wait();
16. }catch(InterruptedException e) {}
17. } else {
18. System.out.println(“Just popped “ + x);
19. }
Search WWH ::
Custom Search