• 手机版

    扫码体验手机版

  • 微信公众号

    扫码关注公众号

国内首家协议开发

软芯音视解码保护平台

在线
客服

发布
需求

在线
聊天

天盟
APP

天盟APP下载

关注
微信

微信扫一扫访问
顶部

生产者消费者模式

package com.umbrella.container.producerConsumer;import java.util.LinkedList;import java.util.concurrent.TimeUnit;public class ProcuderConsumer {    private final LinkedList list = new LinkedList();    private final long MAX = 10;    private int count = 0;    public synchronized void put(T t) {        while (list.size() == MAX) {            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        list.add(t);        ++count;        //不能使用notify,否则可能叫醒的是一个消费者,若此时容器中没有元素,那么消费者就会一直等一直等。        this.notifyAll();    }    public synchronized T get() {        T t = null;        while (list.size() == 0) {            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        t = list.removeFirst();        count--;        this.notifyAll();        return t;    }    public static void main(String[] args) {        ProcuderConsumer pc = new ProcuderConsumer();        //启动消费者进程        for (int i = 0; i < 10; i++) {            new Thread(() -> {                for (int j = 0; j < 5; j++) {                    System.out.println(pc.get());                }            }, "consumer " + i).start();        }        try {            TimeUnit.SECONDS.sleep(2);        } catch (InterruptedException e) {            e.printStackTrace();        }        //启动生产者进程        for (int i = 0; i < 5; i++) {            new Thread(() -> {                for (int j = 0; j < 10; j++) {                    pc.put(Thread.currentThread().getName() + " " + j);                    System.out.println("produce " + j);                }            }, "producer " + i).start();        }    }}这个代码哪里写错了啊 我记得生产者消费者模式是一直运行下去 不会停的 但我写的这个很快就结束了

免责声明:本内容仅代表回答会员见解不代表天盟观点,请谨慎对待。

版权声明:作者保留权利,不代表天盟立场。

使用道具 举报

发新帖

发布任务需求已有1031167位用户正在使用天盟网服务

发布分类: *
任务预算: *
需求内容: *
手机号码: *
任务商家报价为
  • 预算价 :
  • 成交价 :
  • 完工期 :
  • 质保期 :

* 最终任务项目以服务商报价、双方协商为准!