Java Reference
In-Depth Information
20. }
21. }
22. }
23. }
On line 15 the Consumer thread invokes wait on a MyStack2 object if the stack is empty
(returns -1 ). The thread needs to own the lock of stack , which it acquires on line 10.
The following Producer thread calls notify after each push onto the stack:
1. public class Producer extends Thread {
2. private MyStack2 stack;
3.
4. public Producer(MyStack2 stack) {
5. this.stack = stack;
6. }
7.
8. public void run() {
9. while(true) {
10.
11. int random = (int) (Math.random() * 5);
12. stack.push(random);
13. System.out.println(“Just pushed “ + random);
14. synchronized(stack) {
15. System.out.println(“Notifying...”);
16. stack.notify();
17. }
18. try {
19. Thread.sleep(2000);
20. }catch(InterruptedException e) {}
21. }
22. }
23. }
I added a call to Thread.sleep on line 19 of the Producer thread to slow the program
down. The call to notify on line 16 is made on a MyStack2 object. The following code
instantiates a Consumer and Producer , each with a reference to the same MyStack2 object:
4. MyStack2 stack = new MyStack2();
5. Consumer c = new Consumer(stack);
6. c.start();
7.
8. Producer p = new Producer(stack);
9. p.start();
Search WWH ::




Custom Search