生产者消费者的JAVA实现

5 篇文章 0 订阅

生产者消费者问题,对于同一任务队列,生产者线程生产任务数据,消费者线程消费任务数据。

常见实现方式如下:
- 基于同步机制的wait/notify来实现
- 基于并发容器BlockingQueue (BlockingQueue只是接口,有很多不同的具体实现子类)
- 管道通信 PipedInputStream / PipedOutputStream

代码示例如下:

BlockingQueue实现

/**
 * @Author healist
 * @Description
 * @Create 2018-02-21 下午4:20
 */
public class BlockQueue {

    static class Producer extends Thread {

        private boolean isRunning = true;
        private BlockingQueue<String> blockQueue;
        private AtomicInteger count = new AtomicInteger(0);

        public Producer() {}

        public Producer(BlockingQueue<String> queue) {
            this.blockQueue = queue;
        }

        @Override
        public void run() {
            try {
                while (isRunning) {
                    int data = count.incrementAndGet();
                    blockQueue.put(data+"");
                    System.out.println("生产:"+data);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }

        }

        public void stopProducing() {
            isRunning = false;
        }

    }


    static class Consumer extends Thread {
        private boolean isRunning = true;
        private BlockingQueue<String> blockQueue;
        private AtomicInteger count = new AtomicInteger(0);

        public Consumer(BlockingQueue<String> queue) {
            this.blockQueue = queue;
        }

        @Override
        public void run(){
            try {
                while (isRunning) {
                    String data = blockQueue.take();
                    System.out.println("消费:"+ data);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }

    }


    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new LinkedBlockingDeque<String>();
        Producer producer1 = new Producer(queue);
        Producer producer2 = new Producer(queue);
        Producer producer3 = new Producer(queue);
        Consumer consumer1 = new Consumer(queue);
        Consumer consumer2 = new Consumer(queue);
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(producer1);
        service.execute(producer2);
        service.execute(producer3);
        service.execute(consumer1);
        service.execute(consumer2);

        Thread.sleep(10000);

        producer1.stopProducing();
        producer2.stopProducing();
        producer3.stopProducing();

        Thread.sleep(10000);

        service.shutdown();
    }

}

wait/notify的示例代码如下:

// 生产产品
    public void produce(String producer)
    {
        synchronized (list)
        {
            // 如果仓库已满
            while (list.size() == MAX_SIZE)
            {
                System.out.println("仓库已满,【"+producer+"】: 暂时不能执行生产任务!");
                try
                {
                    // 由于条件不满足,生产阻塞
                    list.wait();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

            // 生产产品            
            list.add(new Object());            

            System.out.println("【"+producer+"】:生产了一个产品\t【现仓储量为】:" + list.size());

            list.notifyAll();
        }
    }

    // 消费产品
    public void consume(String consumer)
    {
        synchronized (list)
        {
            //如果仓库存储量不足
            while (list.size()==0)
            {
                System.out.println("仓库已空,【"+consumer+"】: 暂时不能执行消费任务!");
                try
                {
                    // 由于条件不满足,消费阻塞
                    list.wait();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

            list.remove();
            System.out.println("【"+consumer+"】:消费了一个产品\t【现仓储量为】:" + list.size());
            list.notifyAll();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值