• 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 Interaction

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I accept the assertion that when it comes to threads very little is guaranteed.

But I believe that an assumption is being made in the following code.
From Sierra amd Bates pg 529.

This code assumes that ThreadA will get a lock on Thread "b" before "b" can start its loop. Is this a safe way of doing things? Yes I know it is only an example in a book.

Because if the loop in "b" got started before ThreadA got the lock then the following would happen:
ThreadA would be blocked at synchronized(b)
the wait in ThreadA would never receive the notify

Am I getting this right?

Regards

kd



public class ThreadA {
public static void main(String [] args ){
ThreadB b = new ThreadB();
b.start();
synchronized(b) {
System.out.println("ThreadA has the lock");
try {
System.out.println("Waiting for b to complete...");
b.wait();
}
catch (InterruptedException iEx) {}
}
System.out.println("Total is: " + b.total );

}

}


class ThreadB extends Thread {
int total;

public void run() {
synchronized(this) {
System.out.println("ThreadB has the lock");
for(int i = 0; i<100; i++) {
total += i;
}
notify();
}
}

}
 
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think the point of the book is that you shouldn't make those types of assumptions at all!
 
k duffy
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could you suggest how to improve the code?

Please kd
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic