I have read carefully the Oracle documentation and I could not find a design pattern solution for my issue. I have two anonymous threads and one needs to notify the other.
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.a();
obj.b();
}
The MyClass has two different functions, each one launches an anonymous thread. The B person expects to be woken up by his wife, A.
public class MyClass{
public MyClass(){
}
public void a() {
new Thread(new Runnable(){
@Override
public synchronized void run() {
System.out.println("A: I am going to sleep");
try {
Thread.sleep(1000);
System.out.println("A: I slept one full day. Feels great.");
System.out.println("A: Hey B, wake up!");
notifyAll();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
public void b() {
new Thread(new Runnable(){
@Override
public synchronized void run() {
System.out.println("B: I am going to sleep. A, please wake me up.");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("B: Thank you A for waking me up!");
}
}).start();
}
}
Unfortunately, B sleeps forever and could not be woken up by his wife, A.
Output of the program:
A: I am going to sleep
B: I am going to sleep. A, please wake me up.
A: I slept one full day. Feels great.
A: Hey B, wake up!
I understand that A and B are running in two different anonymous threads objects, so A could notify only other A (there are not other wife in the bed so the notify function is useless here).
What is the correct design pattern for this issue?