Friday Dec 15, 2006
Friday Dec 15, 2006
class Run1 implements Runnable {
String s;
boolean wait = true;
Run1(String s) {
this.s = s;
}
public synchronized void run() {
System.out.println("run " + s);
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
}
wait = false;
System.out.println("notify for run " + s);
notifyAll();
}
public synchronized void get() {
while (true) {
try {
System.out.println("wait...");
wait();
if (!(wait)) break;
System.out.println("recv notify...");
} catch (InterruptedException ex) {
}
}
}
}
public class TestThread {
public synchronized void testIt() throws Exception {
Run1 run1 = new Run1("1");
Run1 run2 = new Run1("2");
Thread t1 = new Thread(run1);
t1.start();
Thread t2 = new Thread(run2);
t2.start();
run1.get();
run2.get();
}
public static void main(String[] args) throws Exception {
TestThread t = new TestThread();
t.testIt();
}
}
This is not a deadlock. Rather, the notifyAll() happens before the wait(). So you end up waiting indefinitely.
Posted by SB on December 15, 2006 at 03:02 PM PST #