1.先简单介绍下java.util.concurrent中的几种常见阻塞队列
(1):BlockingQueue
BlockingQueue有四个具体的实现类,根据不同需求,选择不同的实现类:
ArrayBlockingQueue:规定大小的BlockingQueue,其构造函数必须带一个int参数来指明其大小。其所含的对象是以FIFO(先入先出)顺序排序的。
LinkedBlockingQueue:大小不定的BlockingQueue,若其构造函数带一个规定大小的参数,生成的BlockingQueue 有大小限制,若不带大小参数,所生成的BlockingQueue的大小由Integer.MAX_VALUE来决定。其所含的对象是以FIFO顺序排序的。
PriorityBlockingQueue:类似于LinkedBlockingQueue,但其所含对象的排序不是FIFO,而是依据对象的自然排序顺序或者是构造函数所带的Comparator决定的顺序。
SynchronousQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成的。
其中的LinkedBlockingQueue和SynchronousQueue又是比较常用的。
下面以2个例子简单介绍,部分源码如下:
public class BlockingQueueTest {
public static void main(String[] args) {
final BlockingQueue<Integer> queues = new LinkedBlockingDeque<Integer>(3);
final Random random = new Random();
/**
* 生产者
* @author Administrator
*
*/
class Producer implements Runnable {
public void run() {
while (true) {
int i = random.nextInt(100);
// 当队列容量达到时,会自动阻塞
try {
queues.put(i);
if (queues.size() == 3) {
System.out.println("full");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 消费者
* @author Administrator
*
*/
class Consumer implements Runnable {
public void run() {
while (true) {
try {
// 当队列为空时,也会阻塞
queues.take();
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
new Thread(new Producer()).start();
new Thread(new Consumer()).start();
}
}
public class SynchronousQueueTest {
class producer implements Runnable {
private BlockingQueue<String> queues;
List<String> objects = Arrays.asList("one","two","three");
public producer(BlockingQueue<String> q) {
this.queues = q;
}
public void run() {
try {
for (String s : objects) {
queues.put(s);
System.out.println("put:"+s);
}
queues.put("done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class consumer implements Runnable {
private BlockingQueue<String> queues;
public consumer(BlockingQueue<String> q) {
this.queues = q;
}
public void run() {
String obj;
try {
while (!((obj = queues.take()).equals("done"))) {
System.out.println("take:"+obj);
Thread.sleep(3000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
BlockingQueue<String> bq = new SynchronousQueue<String>();
SynchronousQueueTest sqt = new SynchronousQueueTest();
new Thread(sqt.new producer(bq)).start();
new Thread(sqt.new consumer(bq)).start();
}
}