I am preparing for the SCJP exam and I am having trouble with fully understanding synchronization. At line 6, I have read that the thread running in main needs a lock on ‘b’. Why does it need a lock on this object? My understanding is that a synchronized block of code is a protected area that only one thread can be in at any time? Moving on,the thread in main releases this lock and waits for the the thread in ‘b to complete its run method. The thread in ‘b’ is then meant to notify the thread in main that it has completed. However, it does not look like it is notifying any specific thread here. This example is from the Sierra and Bates SCJP book. Any light that can be shed on this would be grately appreciated. thanks
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
**synchronized(b) { //line 6**
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
}
}
}
}
class ThreadB extends Thread {
int total;
public void run() {
System.out.println("K");
synchronized(this) {
for(int i=0;i<100;i++) {
total += i;
}
notify();
}
}
}
Because that is what that line does. It acquires that resource. Other thread can get other synchronized block, but no other thread can acquire a lock on that object.
This is true. The program has no idea which thread will be notify or even if any thread will be notified. You as the developer may conclude there is a particular thread which will be notified, perhaps because its the only thread wait()ing.