阻塞队列 BlockingQueue

java.util.concurrent.BlockingQueue 接口表明了线程安全的队列。
java

BlockingQueue的使用

一个BlockingQueue的典型使用是一个线程不断生产对象往队列里放,另外一个线程往队列里取对象进行消费。
安全

生产线程会保持一致产生新的对象而且插入到队列中,直到队列到达了它的存储上限,生产线程再往队列插入时会发现阻塞,而且一直保持阻塞直到消费线程从队列中取出一个对象。this

消费线程会保持从队列中取出对象而且进行处理,若是消费线程试图从一个空的队列中取出对象,那么消费线程将会阻塞直到生产线程往队列中放入了新的对象。spa

BlockingQueue的方法

BlockingQueue由4中不一样的方法来添加,删除和检测。每组方法有不一样的特色泳衣知足不能当即执行响应请求的操做。
线程

操做 抛出异常 返回操做结果 阻塞 超时
插入 add(o) offer(o) put(o) offer(o,timeout,timeunit)
删除 remove(o) poll(o) take(o) poll(timeout,timeunit)
检测element(o) peek(o)


1.抛出异常:若是对应方法没有当即执行则抛出异常。code

2.返回操做结果:若是对应方法当即执行返回true,不然则返回false(超出队列容量)。对象

3.阻塞:若是对应方法没法当即执行,则将阻塞等待直到方法完成。接口

4.超时:若是对应方法没法当即执行,则会一直等待但不超过给定的超时范围,返回相应的结果。队列

BlockingQueue的实现类

ArrayBlockingQueue
element

DelayQueue

LinkedBlockingDeque

PriorityBlockingQueue

SynchronousQueue

BlockingQueue的示例

// 文章开头生产与消费的示例
public class BlockingQueueExample {

    public static void main(String[] args) throws Exception {

        BlockingQueue queue = new ArrayBlockingQueue(1024);

        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        new Thread(producer).start();
        new Thread(consumer).start();

        Thread.sleep(4000);
    }
}

// 生产者
public class Producer implements Runnable{

    protected BlockingQueue queue = null;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            queue.put("1");
            Thread.sleep(1000);
            queue.put("2");
            Thread.sleep(1000);
            queue.put("3");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

// 消费者
public class Consumer implements Runnable{

    protected BlockingQueue queue = null;

    public Consumer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            System.out.println(queue.take());
            System.out.println(queue.take());
            System.out.println(queue.take());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
相关文章
相关标签/搜索