生产者模式

来源:7-6 用wait/notify实现

YXF_LYY

2021-05-28

老师您好!请问:我这个生产者已经完成生产为什么程序没有结束。是不是消费者消费完了接着通知生产者生产了?但是这个生产者具体是在哪里卡着了呢?这个应该怎样修改。
public class BlockingQueueLYY {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(10);
Consumer consumer = new Consumer(arrayBlockingQueue);
Thread consumerT = new Thread(consumer);
Product product = new BlockingQueueLYY().new Product(arrayBlockingQueue,consumerT);
Thread productT = new Thread(product);

    productT.start();
    Thread.sleep(1000);
    consumerT.start();
}

 class Product implements Runnable{
    private BlockingQueue blockingQueue;
    Thread thread;
    public Product(BlockingQueue blockingQueue,Thread thread){
        this.blockingQueue = blockingQueue;
        this.thread = thread;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                blockingQueue.put(i);
                System.out.println(i+"被放进去了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("生产完成");
        thread.interrupt();
    }
}
static class Consumer implements Runnable{
    private BlockingQueue blockingQueue;
    Consumer(BlockingQueue blockingQueue){
        this.blockingQueue = blockingQueue;
    }
    @Override
    public void run() {
        while (1==1){
            try {
                blockingQueue.take();
                System.out.println("消费了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

}

写回答

1回答

悟空

2021-05-29

生产者结束了,但是消费者还在运行,卡在了

blockingQueue.take();


0
4
YXF_LYY
回复
悟空
谢谢,明白了
2021-05-31
共4条回复

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程