• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread Interaction

 
k duffy
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • 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();
}
}

}
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Could you suggest how to improve the code?

Please kd
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!