I need someone to simplify the wait notify methods for me in java. I've looked at over probably 200 sites now and still don't understand.
I am working on a program that needs to have one thread to be waiting until notify is called from another thread...
class mainClass{
public static void main(String args[])throws Exception{
Thread t1 = new Thread(new Runnable(){
public void run(){
//code inside to make thread t1 wait untill some other thread
//calls notify on thread t1?
}
});
t1.start();
synchronized(t1){
//main thread calling wait on thread t1?
t1.wait();
}
new Thread(new Runnable(){
public void run(){
try{
synchronized(t1){
t1.notify() //?????
}
}catch(Exception e1){}
}
}).start();
}
}
The wait needs to happen in the 1st Runnable and you need to have access to an Object instance to wait on, so the t1 Thread instance won't work. In this code, I've created a separate lock object.
public static void main(String[] args) {
final Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
synchronized(lock) {
try {
lock.wait();
System.out.println("lock released");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
System.out.println("before sleep");
try {
Thread.sleep(1000);
System.out.println("before notify");
synchronized(lock) {
lock.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Using thread notifications can be very hard to test. I'd recommend using a message based approach like Akka.