I was given following code snippet:
public class ThreadTest{
private static class Thread01 extends Thread{
private Thread02 _th2;
public int foo = 0;
public void setThrd02(Thread02 thrd2){
_th2 = thrd2;
}
public void run(){
try{
for(int i=0;i<10;i++) foo += i;
synchronized(this){this.notify();};
synchronized(_th2){_th2.wait();};
System.out.print(" Foo: " + _th2.foo);
}catch(InterruptedException ie){ ie.printStackTrace();}
}
}
private static class Thread02 extends Thread{
private final Thread01 _th1;
public int foo = 0;
public Thread02(Thread01 th1){
_th1 = th1;
}
public void Run(){
try{
synchronized(_th1){_th1.wait();}
foo = _th1.foo;
for(int i=0;i<10;i++) foo += i;
synchronized(this){this.notify();};
}
catch(InterruptedException ie){ie.printStackTrace();}
}
}
public static void main(){
Thread01 th1 = new Thread01();
Thread02 th2 = new Thread02(th1);
th1.setThrd02(th2);
th1.start(); th2.start();
th1.join(); th2.join();
}
}
I think the assumption and corresponding purpose of the code is like th2 run first, it is changed to waiting status by calling _th1.wait(); Then, th1 calculates foo and wake up th2, th1 goes into waiting status; Th2 reads foo from thread1 and updated to 110, then wakes up th1 and th2 exit. Then th1 exit.
The threads could be very risk because it is very possible that thread one runs first and thread 2 will wait forever.
I am not sure any other potential problems of the code.
One possible way that can fix the problem is, for example in the thread1
public class ThreadTest{
private static boolean updated = false; private static boolean finished = false;
private static Thread01 extends Thread{
public void Run(){ // do calcuation while(finished){ wait(); } // output result } }
private static Thread02 extends Thread{ public void run(){
while(false){ wait(); }
foo = th1.foo; // do calculation // similar mechanism to notify thread 1 } }
CyclicBarrier
, to make threads meet at a rendezvous point? – ninjalj