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();
}
}
}