多线程经典案例之生产者消费者

/**
 * 中间商
 **/
class Medium {
    // 当前库存
    private int num = 0;
    // 最大库存
    private static final int TOTAL = 10;

    /**
     * 接收生产数据
     **/
    public synchronized void put() {
        // 判断库存是否已满
        if (num >= TOTAL) {
            try {
                System.out.println("库存已满------------>当前库存:" + num);
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("新增库存------------>当前库存:" + ++num);
            notifyAll();
        }
    }

    /**
     * 获取消费数据
     **/
    public synchronized void take() {
        // 判断库存是否还有
        if (num <= 0) {
            try {
                System.out.println("库存为空------------>当前库存:" + num);
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("减少库存------------>当前库存:" + --num);
            notifyAll();
        }
    }
}

/**
 * 生产者
 **/
class Producer implements Runnable {
    private Medium medium;

    public Producer(Medium medium) {
        this.medium = medium;
    }

    @Override
    public void run() {
        while (true) {
            medium.put();
        }
    }
}

/**
 * 消费者
 **/
class Consumer implements Runnable {
    private Medium medium;

    public Consumer(Medium medium) {
        this.medium = medium;
    }

    @Override
    public void run() {
        while (true) {
            medium.take();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Medium medium = new Medium();
        for (int i = 0; i < 3; i++) {
            new Thread(new Producer(medium)).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(new Consumer(medium)).start();
        }
    }
}
posted @ 2021-05-31 17:09  Gen2021  阅读(32)  评论(0编辑  收藏  举报