public class
Test {
public static void main(
String[] args) {
final Foo f = new Foo();
Thread t = new Thread(new Runnable() {
public void run() {
f.doStuff();
}
}, "Thread1");
Thread g = new Thread("Thread2") {
public void run() {
f.doStuff();
}
};
t.start();
g.start();
}
}
class Foo {
int x = 5;
public void doStuff() {
synchronized (this) {
if (x < 10) {
// nothing to do
try {
x += 5;
System.out.println(Thread.currentThread().getName()
+ " is waiting.");
this.wait();
System.out.println(Thread.currentThread().getName()
+ " is wait is over.");
} catch (InterruptedException ex) {
}
} else {
System.out.println("x is :" + x);
if (x >= 10) {
this.notify();
}
}
}
}
}
how can g.start() access the synchronized and call notify() code when the lock of the object is possessed by wait() which was executed earlier ?