为了账号安全,请及时绑定邮箱和手机立即绑定

生产者消费者模式

生产者消费者模式

fenkapian 2018-05-01 23:39:19
package com.umbrella.container.producerConsumer; import java.util.LinkedList; import java.util.concurrent.TimeUnit; public class ProcuderConsumer<T> {     private final LinkedList<T> 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<String> 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();         }     } }这个代码哪里写错了啊 我记得生产者消费者模式是一直运行下去 不会停的 但我写的这个很快就结束了
查看完整描述

目前暂无任何回答

  • 0 回答
  • 0 关注
  • 1212 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信