Hi All, I have a doubt related to this wait() and notify(). Please look at the following code:
1. class ThreadA {
2. public static void main(String [] args) {
3. ThreadB b = new ThreadB();
4. b.start();
5.
6. synchronized(b) {
7. try {
8. System.out.println("Waiting for b to complete...");
9. b.wait();
10. System.out.println("After waiting");
11. } catch (InterruptedException e) {}
12. System.out.println("Total is: " + b.total);
13. }
14. }
15. }
16.
17. class ThreadB extends
Thread {
18. int total;
19.
20. public void run() {
21. synchronized(this) {
22. for(int i=0;i<100;i++) {
23. total += i;
24. }
25. notify(); 26. }
27. }
28. }
In line number no 25, the notify() method is included. If I remove this notify(), will the thread that invokes the wait() method will
wait for ever??.
I tried removing the notify() method. I get the same results irrespective of the presence of notify() method.
Output(Irrespective of whether I include notify() or not:
Wating for b to complete
0
1
3
6
10
15
21
28
36
45
After waiting Please explain whether the notify() method is mandatory if we call the wait() method or once the called thread is completed, will the waiting method resume by itself..
Thanks
Loga
[ November 07, 2008: Message edited by: Loganathan Karunakaran ]