BlockingQueue阻塞队列和生产者-消费者模式

来源:互联网 发布:魔兽美工代码编辑器 编辑:程序博客网 时间:2024/05/16 23:39

BlockingQueue阻塞队列是一个线程安全的类,如果队列为空时,那么take获取元素操作将一直阻塞;当队列已满时(假设建立的队列有指定容量大小),则put插入元素的操作将一直阻塞,知道队列中出现可用的空间,在生产者-消费者模式中,这种队列非常有用。

在基于阻塞队列的生产者-消费者模式中,当数据生成时,生产者将数据放入队列,而当消费者准备处理数据时,从队列中获取数据。

以下是用BlockingQueue阻塞队列实现的一个生产者消费者的示例:

import java.util.Random;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;class Producer implements Runnable{private final BlockingQueue<Integer> producerQueue;private final Random random = new Random();public Producer(BlockingQueue<Integer> producerQueue){this.producerQueue = producerQueue;}public void run() {while(true){try {producerQueue.put(random.nextInt(100));Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}}}class Consumer implements Runnable{private final BlockingQueue<Integer> producerQueue;public Consumer(BlockingQueue<Integer> producerQueue){this.producerQueue = producerQueue;}public void run() {while(true){try {Integer i = producerQueue.take();System.out.println(i);Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}}}}public class BlockingQueueTest {public static void main(String[] args) {BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>(10);for(int i = 0 ; i < 3; i++){new Thread(new Producer(queue)).start();}for(int i = 0 ; i < 1; i++){new Thread(new Consumer(queue)).start();}}}
这种方式的生产者和消费者,生产者不用知道有多少个消费者,甚至不用知道有多少个生产者,对消费者来说也是一样,只跟队列打交道,很好的实现了生产者和消费者的解耦。

0 0
原创粉丝点击