美文网首页
BlockingQueue

BlockingQueue

作者: Jokerone_ | 来源:发表于2017-04-06 10:50 被阅读0次

ArrayBlockingQueue源码分析
LinkedBlockingQueue源码分析

使用阻塞队列实现的生产者-消费者模型

public class Test {
    private int queueSize = 10;
    private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(queueSize); 
    public static void main(String[] args)  {
        Test test = new Test();
        Producer producer = test.new Producer();
        Consumer consumer = test.new Consumer();         
        producer.start();
        consumer.start();
    }

    class Consumer extends Thread{  
        @Override
        public void run() {
            while(true){
                try {
                    queue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }   
    }

    class Producer extends Thread{    
        @Override
        public void run() {         
            while(true){
                try {
                    queue.put(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }     
    }
}

相关文章

网友评论

      本文标题:BlockingQueue

      本文链接:https://www.haomeiwen.com/subject/qgprottx.html