频道栏目
首页 > 程序开发 > 软件开发 > Java > 正文
java开发中生产者消费者问题实现教程
2018-02-22 10:33:14      个评论    来源:Healist的博客  
收藏   我要投稿

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

常见实现方式如下:
- 基于同步机制的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 blockQueue;
        private AtomicInteger count = new AtomicInteger(0);

        public Producer() {}

        public Producer(BlockingQueue 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 blockQueue;
        private AtomicInteger count = new AtomicInteger(0);

        public Consumer(BlockingQueue 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 queue = new LinkedBlockingDeque();
        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();
        }
    }
点击复制链接 与好友分享!回本站首页
上一篇:Missing artifact javax.jms:jms:jar:1.1
下一篇:JAVA代码—算法基础:活动安排问题(贪心算法)
相关文章
图文推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站