I am learning multi threading and I am trying to understand how to use wait and notify methods of Object class. I have gone through this link https://www.journaldev.com/1037/java-thread-wait-notify-and-notifyall-example and have written the following program
Waiter
public class Waiter implements Runnable {
private Message m;
public Waiter(Message m) {
this.m = m;
}
public void run() {
String name = Thread.currentThread().getName();
System.out.println(t1 + " thread waiting for message");
synchronized (m) {
try {
m.wait();
System.out.println(t1 + " " + m.getText());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(t1 + " thread waiting for message");
}
}
Notifier
public class Notifier implements Runnable {
private Message m;
public Notifier(Message m) {
this.m = m;
}
public void run() {
synchronized (m) {
try {
Thread.sleep(2000);
m.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Test
public class WaitNotifyTest {
public static void main(String[] str) {
Message m = new Message("hello");
new Thread(new Waiter(m), "t1").start();
new Thread(new Waiter(m), "t2").start();
new Thread(new Notifier(m)).start();
}
}
When I execute the program, it sometimes terminates properly, sometimes it waits indefinitely, sometimes one of the thread terminates and the other waits indefinitely. Can anyone please tell me what is wrong here?
Also I want to know few examples of real time applications of wait and notify methods.