/**
* 开启四个线程 两个waitThread和 两个notifyThread
* 使用notifyThread唤醒waitThread线程
*/
public class NotifyExample {
public static void main(String[] args) {
final Object lock = new Object();
Thread waitThread1 = new Thread(() -> {
synchronized (lock) {
System.out.println(LocalTime.now() + " " + Thread.currentThread().getName() +" WaitThread: Going to wait");
try {
lock.wait(); // wait until notified
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(LocalTime.now() + " " + Thread.currentThread().getName() + " WaitThread: Woke up");
}
});
Thread waitThread2 = new Thread(() -> {
synchronized (lock) {
System.out.println(LocalTime.now() + " " + Thread.currentThread().getName() + " WaitThread: Going to wait");
try {
lock.wait(); // wait until notified
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(LocalTime.now() + " " + Thread.currentThread().getName() + " WaitThread: Woke up");
}
});
Thread notifyThread1 = new Thread(() -> {
try {
Thread.sleep(4000); // sleep for 2 seconds
} catch (InterruptedException e) {
System.out.println(e);
}
synchronized (lock) {
System.out.println(LocalTime.now() + " " + Thread.currentThread().getName() + " NotifyThread: Notifying the waiting thread");
lock.notify(); // notify the waiting thread
}
});
Thread notifyThread2 = new Thread(() -> {
try {
Thread.sleep(6000); // sleep for 2 seconds
} catch (InterruptedException e) {
System.out.println(e);
}
synchronized (lock) {
System.out.println(LocalTime.now() + " " + Thread.currentThread().getName() + " NotifyThread: Notifying the waiting thread");
lock.notify(); // notify the waiting thread
}
});
waitThread1.start();
waitThread2.start();
notifyThread1.start();
notifyThread2.start();
}
}
输出结果
11:31:15.969 Thread-0 WaitThread: Going to wait
11:31:15.969 Thread-1 WaitThread: Going to wait
11:31:19.946 Thread-2 NotifyThread: Notifying the waiting thread
11:31:19.946 Thread-0 WaitThread: Woke up
11:31:21.945 Thread-3 NotifyThread: Notifying the waiting thread
11:31:21.945 Thread-1 WaitThread: Woke up
Process finished with exit code 0