• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread'd wait() related >>>>>>>

 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
reply
    Bookmark Topic Watch Topic
  • New Topic