S
stixwix
Hi,
Can anyone explain this behaviour? It is basically the minimum amount
of code to set up a thread that waits until it is notified by the main
thread.
In this code the notify does not work because of the way it uses an
instance of the Outer class to specify the Runnable passed to the
Thread constructor.
However, if the first two lines of the test method are replaced by:
Thread t = new Thread(new Worker());
it works as expected.
public class Outer {
private Object lock = new Object();
public class Worker implements Runnable {
public void run(){
synchronized(lock){
try {
lock.wait();
}
catch (InterruptedException e) {}
}
}
}
public void test(){
Outer out = new Outer();
Thread t = new Thread(out.new Worker());
t.start();
// allow enough time for the thread to enter wait
Thread.sleep(100);
synchronized(lock) {
lock.notifyAll();
}
}
}
Can anyone explain this behaviour? It is basically the minimum amount
of code to set up a thread that waits until it is notified by the main
thread.
In this code the notify does not work because of the way it uses an
instance of the Outer class to specify the Runnable passed to the
Thread constructor.
However, if the first two lines of the test method are replaced by:
Thread t = new Thread(new Worker());
it works as expected.
public class Outer {
private Object lock = new Object();
public class Worker implements Runnable {
public void run(){
synchronized(lock){
try {
lock.wait();
}
catch (InterruptedException e) {}
}
}
}
public void test(){
Outer out = new Outer();
Thread t = new Thread(out.new Worker());
t.start();
// allow enough time for the thread to enter wait
Thread.sleep(100);
synchronized(lock) {
lock.notifyAll();
}
}
}