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. } catch (InterruptedException e) {}
11. System.out.println("Total is: " + b.total);
12. }
13. }
14. }
15.
16. class ThreadB extends
Thread {
17. int total;
18.
19. public void run() {
20. synchronized(this) {
21. for(int i=0;i<100;i++) {
22. total += i;
23. }
24. notify();
25. }
26. }
27. }
This program contains two objects with threads: ThreadA contains the main
thread and ThreadB has a thread that calculates the sum of all numbers from 0
through 99.
**********************************************
I have pasted above code from K n B's page 720.according to book there are two objects, But as per my knowledge there is only one object ie 'b'.???
is it right to say that we are synchronizing object(b) at line 6 rather than method.???
according to me main thread starts executing ...encounters start() at line 4 and starts new thread and moves to line 18.concurrently main thread is executing at line 6 it acquires lock of 'b' and at line 9 it starts waiting to be notified releasing it's lock.
*******************************************************
And if in the above program i make line 24 as comment.It should not print 'total', But it's printing???
if there is no notify(),how the waiting thread wake up???
Please clarify this
Thanks
Deepak