How to wait for a variable to be set?
Hi,
I need to wait for a variable to be set. I tried this, but it didn't work (IllegalMonitorStateException). How to do it?
Thanks!
publicclass MyClass{
private Boolean succed =null;
publicstaticboolean doStuff(){
MyClass my =new MyClass();
while (my.succed ==null){
try{
my.wait();
}catch (InterruptedException e){}// Nothing
}
return my.succed.booleanValue();
}
// and elsewhere set succed to Boolean.TRUE / FALSE and call notifyAll()
}
Try this:
import java.util.*;
public class Test {
private Boolean flag = null;
public synchronized boolean waitForFlag() {
boolean res;
while(flag == null) {
try { wait(); } catch(InterruptedException e) {}
}
res = flag.booleanValue();
flag = null;
notifyAll();
return res;
}
public synchronized void setFlag(boolean flag) {
while(this.flag != null) {
try { wait(); } catch(InterruptedException e) {}
}
this.flag = new Boolean(flag);
notifyAll();
}
public static void main(String[] args) {
final Test t = new Test();
new Thread() {
public void run() {
System.out.println("1: " + t.waitForFlag());
}
}.start();
new Thread() {
public void run() {
System.out.println("2: " + t.waitForFlag());
}
}.start();
try { Thread.sleep(5000); } catch(InterruptedException e) {}
t.setFlag(true);
t.setFlag(false);
}
}