Java面试题(十四) 传统版生产者消费者模式

一. 生产者消费者模式

1. 定义:

生产者消费者问题(英语:Producer-consumer problem),也称有限缓冲问题(英语:Bounded-buffer problem),是一个多线程同步问题的经典案例。
该问题描述了两个共享固定大小缓冲区的线程——即所谓的“生产者”和“消费者”——在实际运行时会发生的问题。
生产者的主要作用是生成一定量的数据放到缓冲区中,然后重复此过程。与此同时,
消费者也在缓冲区消耗这些数据。
该问题的关键就是要保证生产者不会在缓冲区满时加入数据,
消费者也不会在缓冲区中空时消耗数据。(摘自百度百科)

2. 模拟案例:

一个初始为0的变量,
2个线程 一个加1一个减1,
玩5轮。

3. 代码演示:

//资源类
class shareData {

    private int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void add() throws Exception {

        lock.lock();
        try {

            //1. 判断是否需要生产
            while (num != 0) {  //在多线程下判断使用 while
                //等待,不能生产
                condition.await(); //新版玩法
            }
            //2. 生产
            num++;
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            //3. 唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void sub() throws Exception {

        lock.lock();
        try {

            //1. 判断是否需要消费
            while (num == 0) {  //在多线程下判断使用 while
                //等待,不能消费
                condition.await(); //新版玩法
            }
            //2. 消费
            num--;
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            //3. 唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
public static void main(String[] args) {

        shareData shareData = new shareData();

        //开启生产者线程
        new Thread(() -> {
            //开 5 轮
            for (int i = 1; i <= 5; i++) {
                try {
                    shareData.add();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "Producer").start();

        //开启消费者线程
        new Thread(() -> {
            //开 5 轮
            for (int i = 1; i <= 5; i++) {
                try {
                    shareData.sub();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "Consumer").start();
    }

运行结果
在这里插入图片描述

总结:在多线程下操作判断,记得使用while不要使用if。

猜你喜欢

转载自blog.csdn.net/w_x_A__l__l/article/details/106905642