线程之间的通信问题 :生产者和消费者问题! 等待唤醒,通知唤醒

传统  synchronized  锁   这个例子在两个线程下是可以稳定运行,但要是再加两个线程下去的话会出问题
为什么呢 因为在下面判断是if 因为if只会走一次
把if改为while,while一旦被修改了,另一个将进去等待
/*
* 线程之间的通信问题 :生产者和消费者问题! 等待唤醒,通知唤醒 * 线程交替执行 A B 操作同一个变量 num=0 * A num+1 * B num-1 * * */ public class A { public static void main(String[] args) { Date date = new Date(); new Thread(()->{ for (int i = 0; i < 10; i++) { try { date.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } },"A").start(); new Thread(()->{ for (int i = 0; i < 10; i++) { try { date.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } },"B").start(); } //判断等待,业务,通知 class Date {//数字资源 static Logger logger = Logger.getLogger(String.valueOf(A.class)); private int number = 0; public synchronized void increment() throws InterruptedException { if(number != 0){ this.wait(); } number++; logger.info(Thread.currentThread().getName()+"->"+number); //通知其他线程,我+1好了 this.notifyAll(); } public synchronized void decrement() throws InterruptedException { if(number == 0){ //等待 this.wait(); } number--; // System.out.println(Thread.currentThread().getName()+"->"+number); logger.info(Thread.currentThread().getName()+"->"+number); //通知其他线程,我-1好了 this.notifyAll(); } }
原文地址:https://www.cnblogs.com/rzkwz/p/12612793.html