使用BlockingQueue来实现产生都与消费者的例子,比起前面第三章的用法会更加简单,因为它不需要去解决同步问题。下面的例子使用BlockingQueue和ArrayBlockingQueue实现生产者的消费者的例子。
package com.owen.thread.chapter8;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PC
{
public static void main(String[] args)
{
final BlockingQueue<Character> bq;
bq = new ArrayBlockingQueue<Character>(26);
final ExecutorService executor = Executors.newFixedThreadPool(2);
Runnable producer = () -> {
for (char ch = 'A'; ch <= 'Z'; ch++)
{
try
{
bq.put(ch);
System.out.printf("%c produced by " + "producer.%n", ch);
} catch (InterruptedException ie)
{
}
}
};
executor.execute(producer);
Runnable consumer = () -> {
char ch = '\0';
do
{
try
{
ch = bq.take();
System.out.printf("%c consumed by " + "consumer.%n", ch);
} catch (InterruptedException ie)
{
}
} while (ch != 'Z');
executor.shutdownNow();
};
executor.execute(consumer);
}
}
上面的例子中,使用BlockingQueue()的put()和take()方法,分别代表,在阻塞的队列中放入一个对象,和在阻塞的队列中移除一个对象。当没有空间放入一个对象时,put()方法会阻塞;当队列为空时,take()会阻塞。
BlockingQueue确保一个字母在生产之前不会被消费,这个应用会有输出提示。例子,执行这个程序会得到如下的输出:
A produced by producer.
B produced by producer.
A consumed by consumer.
B consumed by consumer.
C consumed by consumer.
C produced by producer.
••••••