I'm looking at some notify/wait examples and came across this one. I understand a synchronized block essentially defines a critical section, but doesn't this present a race condition? Nothing specifies which synchronized block is entered first.
public class ThreadA {
public static void main(String[] args){
ThreadB b = new ThreadB();
b.start();
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();
}
}
}
Output per website:
Waiting for b to complete...
Total is: 4950
notify()
before the main thread callswait()
. – Leantosynchronized
block as preventing a race. It merely limits the scope of the race. It's like a section of an automobile race course where the track is too narrow cars to overtake one another. They're still racing, but they have to go through that one section single-file. Same goes for thesynchronized
block: The threads aren't racing in here, but they race to get here, and they race everywhere else. – Jabewait()
in a loop. – Sender