package com.my.demo;
import java.io.IOException;
public class WaitNotifyDemo {
public static void main(String[] args) throws InterruptedException, IOException {
Object lock = new Object();
//They share the same lock.
new NotifyThread("notify01", lock).start();
new WaitThread("waiter01", lock).start();
new WaitThread("waiter02", lock).start();
}
}
class WaitThread extends Thread {
private Object lock;
public WaitThread(String name, Object lock) {
super(name);
this.lock = lock;
}
public void run() {
synchronized (lock) {
System.out.println(getName() + " waiting!");
long waitTime = System.currentTimeMillis();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
waitTime = System.currentTimeMillis() - waitTime;
System.out.println(getName() + " wait time: " + waitTime);
}
}
}
class NotifyThread extends Thread {
private Object lock;
public NotifyThread(String name, Object lock) {
super(name);
this.lock = lock;
}
public void run() {
try {
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
synchronized (lock) {
lock.notifyAll();
}
}
};