Java多线程消费者和生产者模式并发死锁问题解决

以下是文章的主要核心点

  1. 文中采用Stream流的方式创建多个生产者和消费者
  2. 利用对象的wait()进行阻塞
  3. 利用synchronized 的原理
  4. 创建唯一的Monitor的LOCK对象
  5. 通过notifyAll()唤醒阻塞,此处不能用notify()

import java.util.stream.Stream;

public class ProduceConsumer {
    private int i;
    final private Object LOCK = new Object();
    private volatile boolean isProduced = false;

    public void produce() throws InterruptedException {
        synchronized (LOCK) {
            if (isProduced) {
                LOCK.wait();
            } else {
                i++;
                System.out.println(Thread.currentThread().getName()+"  P-----> " + i);
                isProduced = true;
                LOCK.notifyAll();
            }
        }
    }

    public void consumer() throws InterruptedException {
        synchronized (LOCK) {
            if (isProduced) {
                System.out.println(Thread.currentThread().getName()+"  C-----> " + i);
                isProduced = false;
                LOCK.notifyAll();
            } else {
                LOCK.wait();
            }
        }
    }

    public static void main(String[] args) {
        ProduceConsumer produceConsumer = new ProduceConsumer();
        Stream.of("P1", "P2", "p3").forEach(name -> {
            new Thread(() -> {
                while (true) {
                    try {
                        produceConsumer.produce();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },name).start();
        });
        Stream.of("C1", "C2", "C3").forEach(name -> {
            new Thread(() -> {
                while (true) {
                    try {
                        produceConsumer.consumer();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },name).start();
        });
        
    }
}

posted @   飞航之梦  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示