代码如下
运行结果
注意两点就可以:一个是判断仓库是否有货,用while;另一个是,多线程用notifyAll,不要用notify
本文链接:https://liuyanzhao.com/4465.html
- package com.liuyanzhao.multi_thread;
- /**
- * 注意
- * 1、判断仓库有否有货是否,必须用while,而不能用if,
- * 作用是让线程醒过来的时候,还要判断是否为空,
- * 如果用if的话,就不会判断,直接往下走,
- * 会导致连续生产或者消费。
- * 2、超过两个线程的时候,用notifyAll唤醒,不要用notify
- *
- * @author 言曌
- * @date 2018/6/21 下午5:13
- */
- class Resource {
- private boolean isEmpty = true;
- private int count = 0;
- public synchronized void put() { //生产
- //如果不是空,就wait()
- while (!isEmpty) {
- try {
- wait();//放弃锁,在这里等,本线程暂停
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- count++;
- //否则,执行下面代码
- System.out.println(Thread.currentThread().getName() + " 生产1个,剩余" + count + "个");
- isEmpty = false;
- this.notifyAll();//释放锁,所有wait中的线程重新唤醒,开始抢cpu执行权
- }
- public synchronized void get() { //消费
- //如果是空的,就wait()
- while (isEmpty) {
- try {
- wait();//放弃锁,在这里等,本线程暂停
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- count--;
- //否则,执行下面代码
- System.out.println(Thread.currentThread().getName() + " 消费1个,剩余" + count + "个");
- isEmpty = true;
- this.notifyAll();//释放锁,所有wait中的线程重新唤醒,开始抢cpu执行权
- }
- }
- class Producer implements Runnable {
- private Resource res;
- public Producer(Resource res) {
- this.res = res;
- }
- @Override
- public void run() {
- while (true) {
- res.put();
- }
- }
- }
- class Consumer implements Runnable {
- private Resource res;
- public Consumer(Resource res) {
- this.res = res;
- }
- @Override
- public void run() {
- while (true) {
- res.get();
- }
- }
- }
- public class ProducerConsumerDemo {
- public static void main(String[] args) {
- Resource r = new Resource();
- Producer producer = new Producer(r);
- Consumer consumer = new Consumer(r);
- Thread t1 = new Thread(producer, "甲工人");
- Thread t2 = new Thread(producer, "乙工人");
- Thread t3 = new Thread(consumer, "A用户");
- Thread t4 = new Thread(consumer, "B用户");
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
运行结果
注意两点就可以:一个是判断仓库是否有货,用while;另一个是,多线程用notifyAll,不要用notify
本文链接:https://liuyanzhao.com/4465.html
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏