1、wait()、notify/notifyAll() 方法是Object的本地final方法,无法被重写。
2、wait()执行后拥有当前锁的线程会释放该线程锁,并处于等待状态(等待重新获取锁)
3、notify/notifyAll() 执行后会唤醒处于等待状态线程获取线程锁、只是notify()只会随机唤醒其中之一获取线程锁,notifyAll() 会唤醒所有处于等待状态的线程抢夺线程锁。
三个方法的最佳实践代码如下:
public class WaitAndNotify { public static void main(String[] args) { MethodClass methodClass = new MethodClass(); Thread t1 = new Thread(() -> { try { methodClass.product(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }, "t1"); Thread t2 = new Thread(() -> { try { methodClass.customer(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }, "t2"); Thread t3 = new Thread(() -> { try { methodClass.customer(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }, "t3"); t1.start(); t2.start(); t3.start(); } } class MethodClass { // 定义生产最大量 private final int MAX_COUNT = 20; int productCount = 0; public synchronized void product() throws InterruptedException { while (true) { System.out.println(Thread.currentThread().getName() + ":::run:::" + productCount); Thread.sleep(10); if (productCount >= MAX_COUNT) { System.out.println("货舱已满,,.不必再生产"); wait(); }else { productCount++; } notifyAll(); } } public synchronized void customer() throws InterruptedException { while (true) { System.out.println(Thread.currentThread().getName() + ":::run:::" + productCount); Thread.sleep(10); if (productCount <= 0) { System.out.println("货舱已无货...无法消费"); wait(); }else { productCount--; } notifyAll(); } } }
结果:
t1:::run:::0 t1:::run:::1 t1:::run:::2 t1:::run:::3 t1:::run:::4 t1:::run:::5 t1:::run:::6 t1:::run:::7 t1:::run:::8 t1:::run:::9 t1:::run:::10 t1:::run:::11 t1:::run:::12 t1:::run:::13 t1:::run:::14 t1:::run:::15 t1:::run:::16 t1:::run:::17 t1:::run:::18 t1:::run:::19 t1:::run:::20 货舱已满,,.不必再生产 t3:::run:::20 t3:::run:::19 t3:::run:::18 t3:::run:::17 t3:::run:::16 t3:::run:::15 t3:::run:::14 t3:::run:::13 t3:::run:::12 t3:::run:::11 t3:::run:::10 t3:::run:::9 t3:::run:::8 t3:::run:::7 t3:::run:::6 t3:::run:::5 t3:::run:::4 t3:::run:::3 t3:::run:::2 t3:::run:::1 t3:::run:::0 货舱已无货...无法消费 t2:::run:::0 货舱已无货...无法消费 t1:::run:::0 t1:::run:::1 t1:::run:::2 t1:::run:::3 t1:::run:::4 t1:::run:::5 t1:::run:::6 t1:::run:::7 t1:::run:::8 t1:::run:::9 t1:::run:::10 t1:::run:::11 t1:::run:::12 t1:::run:::13 t1:::run:::14 t1:::run:::15 t1:::run:::16 t1:::run:::17 t1:::run:::18 t1:::run:::19 t1:::run:::20 货舱已满,,.不必再生产 t2:::run:::20 t2:::run:::19 t2:::run:::18 t2:::run:::17 t2:::run:::16 t2:::run:::15 t2:::run:::14 t2:::run:::13 t2:::run:::12 t2:::run:::11 t2:::run:::10 t2:::run:::9 t2:::run:::8 t2:::run:::7 t2:::run:::6 t2:::run:::5 t2:::run:::4 t2:::run:::3 t2:::run:::2 t2:::run:::1 t2:::run:::0 货舱已无货...无法消费