为啥我的生产者消费者会卡住?

public class ProducerConsumer {

    //产品
    static class Product {
        String name;

        public Product(String n) {
            this.name = n;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    //阻塞队列
    static BlockingQueue<Product> queue = new LinkedBlockingDeque<>(10);

    //生产者
    static class Producer implements Runnable {
        String name;

        public Producer(String name) {
            this.name = name;
        }

        void produce(Product p) throws InterruptedException {
            //阻塞等待,等有空间放则返回
            queue.put(p);
            //放入成功则返回 true,失败则返回 false
            //queue.offer(p);
            System.out.println("生产:" + p.name);
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    produce(new Product("" + i));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //消费者
    static class Consumer implements Runnable {
        String name;

        public Consumer(String name) {
            this.name = name;
        }

        void consume() throws InterruptedException {
            //阻塞等待
            Product p = queue.take();
            //没有则返回 null
            //Product p = queue.poll();
            System.out.println("消费:" + p.name);
        }

        @Override
        public void run() {
            try {
                consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //测试
    public static void main(String[] args) {
        Consumer consumer = new Consumer("消费者");
        Producer producer = new Producer("生产者");
        for (int i = 0; i < 5; i++) {
            new Thread(consumer, "消费者线程" + i).start();
            new Thread(producer, "生产者线程" + i).start();
        }
    }
}
#笔试题目#
全部评论
没有处理临界区
点赞 回复 分享
发布于 2019-07-13 21:52

相关推荐

01-15 13:52
已编辑
河南大学 Java
六年要多久:标准头像,不吃香菜😂
点赞 评论 收藏
分享
评论
点赞
3
分享

创作者周榜

更多
牛客网
牛客企业服务