zoukankan      html  css  js  c++  java
  • 线程之间的通信问题 :生产者和消费者问题! 等待唤醒,通知唤醒

    传统  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(); } }
  • 相关阅读:
    python批量安装模块 批量导出模块
    java 基础学习1
    linux 命令小记
    nosql数据库-mongodb
    python 列表大小快速比较方法
    nvidia-smi 系列命令,查看gpu ,显存信息
    pipinstaller
    pyinstaller 模块-python文件生成exe可执行文件
    git命令提交到github代码
    subprocess.Popen()
  • 原文地址:https://www.cnblogs.com/rzkwz/p/12612793.html
Copyright © 2011-2022 走看看