I'm new to Java multithreading and written a small program to test how the wait() and notifyAll() methods interact with each other. But why doesn't this program work?
package sample;
public class Main {
public static void main(String[] args) {
new Thread(new MyWriter()).start();
new Thread(new MyReader()).start();
}
}
class MyReader implements Runnable {
@Override
public synchronized void run() {
while(true) {
notifyAll();
}
}
}
class MyWriter implements Runnable {
@Override
public synchronized void run() {
while(true) {
try {
System.out.println("Waiting...");
wait();
System.out.println("Wait Terminated");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
When running, I expected the output to be
Waiting...
Wait Terminated
But it outputs
Waiting...
And just waits forever until I terminate it manually.