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

生产者消费者模式死锁

生产者消费者模式死锁

fenkapian 2018-10-21 21:41:44
public class ProducerConsumer<T> {     private final LinkedList<T> linkedList = new LinkedList<>();     private final long MAX = 10;     private int count = 0;     public synchronized void put(T t) {         while (linkedList.size() == MAX) {             try {                 this.wait();             } catch (InterruptedException e) {                 e.printStackTrace();             }         }         linkedList.add(t);         count++;         this.notifyAll();     }     public synchronized T get() {         while (linkedList.size() == 0) {             try {                 this.wait();             } catch (InterruptedException e) {                 e.printStackTrace();             }         }         T t = null;         t = linkedList.removeFirst();         count--;         this.notifyAll();         return t;     }     public static void main(String[] args) {         ProducerConsumer<String> pc = new ProducerConsumer<>();         for (int i = 0; i < 2; i++) {             new Thread(() -> {                 for (int j = 0; j < 6; j++) {                     pc.put(Thread.currentThread().getName() + " ");                     try {                         Thread.sleep(2);                     } catch (InterruptedException e) {                         e.printStackTrace();                     }                 }             }, "producer " + i).start();         }         for (int i = 0; i < 10; i++) {             new Thread(() -> {                 for (int j = 0; j < 5; j++) {                     System.out.println(pc.get());                     try {                         Thread.sleep(2);                     } catch (InterruptedException e) {                         e.printStackTrace();                     }                 }             }, "consumer " + i).start();         }     } }代码运行就死锁  哪里错了啊
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 1630 浏览

添加回答

举报

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