Reputation: 18171
Is there any difference of placing timlesProc(100);
inside or outside synchronized
block like shown commented line in ThreadA.
According to my understanding there is no difference, because both threads are in running mode and both can be executed in the same time. But according experiments, when timlesProc(100);
is inside synchronized
- it always runs first, then b.sync.wait();
and no 'wait forever' problem. When timlesProc(100);
outside synchronized
- I always get 'waiting forever'. Why it is so, or my understanding is not correct?
class ThreadA {
public static void timlesProc(int count)
{
for(int i=0;i<count;i++)
{
System.out.println(Thread.currentThread().getName()+" "+ Integer.toString(i));
}
}
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
//timlesProc(100);
synchronized(b.sync)
{
timlesProc(100);
try
{
System.out.println("Waiting for b to complete...");
b.sync.wait();
System.out.println("waiting done");
} catch (InterruptedException e) {}
}
}
}
class ThreadB extends Thread {
Integer sync = new Integer(1);
public void run() {
synchronized(sync)
{
sync.notify();
System.out.println("notify done");
}
}
}
Upvotes: 0
Views: 92
Reputation: 7812
Actually, even if the timlesProc
call is inside the synchronized block, there is still a race condition, just less likely to happen.
If b.start()
happens, and it aquires the sync lock before the main thread, then it will still notify first causing the same problem that Sotirios Delimanolis mentions in his answer.
Upvotes: 2
Reputation: 279960
You have a race condition. If the timlesProc
method is outside the synchronized
, it's very probable that you will have a context switch and the other Thread
will be able to execute acquiring the lock and notifying the main
Thread (even if it wasn't waiting). Then when you get to
b.sync.wait();
you wait forever because there is nothing left to notify()
it.
If you put the timlesProc
inside the synchronized
, you reach the wait()
and then get notified. The program then finishes.
See Cruncher's answer for another possibility of your program waiting forever.
Upvotes: 4