zoukankan      html  css  js  c++  java
  • 生产者-消费者 用阻塞队列实现

    使用阻塞队列代码要简单得多,不需要再单独考虑同步和线程间通信的问题

    在并发编程中,一般推荐使用阻塞队列

    public class BolckQuene_Pro_Con
    {
        private int queueSize = 10;//队列允许存放的最大数
        private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(queueSize);//阻塞队列
        
        public static void main(String[] args)  {
            BolckQuene_Pro_Con test = new BolckQuene_Pro_Con();
            Producer producer = test.new Producer();
            Consumer consumer = test.new Consumer();
             
            producer.start();
            consumer.start();
        }
        
        class Consumer extends Thread{
            @Override
            public void run() {
                consume();
            }
            private void consume() {
                while(true){
                    
                    try {
                        Thread.sleep(300);
                        queue.take();
                        System.out.println("【消费者】从队列取走一个元素,队列剩余"+queue.size()+"个元素");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
         
        class Producer extends Thread{
            @Override
            public void run() {
                produce();
            }
            private void produce() {
                while(true){
                    try {
                        Thread.sleep(200);
                        queue.put(1);
                        System.out.println("【生产者】向队列取中插入一个元素,队列中元素:"+queue.size());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    逃避不一定躲得过,面对不一定最难过
  • 相关阅读:
    详细的git入门级别,从安装到实战
    Linux安装maven超级详细步骤
    比较全的开源软件镜像地址
    区块链应用领域
    区块链来源比特币,区块链基础构造
    xpath定位总结--精简版
    python装饰器
    python六剑客
    Python断言方法:assert
    python3对excel读写openpyxl
  • 原文地址:https://www.cnblogs.com/yangzhenlong/p/5231659.html
Copyright © 2011-2022 走看看