1.BlockingQueue:支持两个附加操作的 Queue,这两个操作是:检索元素时等待队列变为非空,以及存储元素时等待空间变得可用。
2.BlockingQueue 不接受 null 元素。
3.BlockingQueue 可以是限定容量的。
4.BlockingQueue 实现是线程安全的。Queue不是线程安全的。因此可以将Blockingqueue用于用于生产者-使用者队列。
- import java.util.*;
- import java.util.concurrent.*;
- class Producer
- implements Runnable
- {
- private BlockingQueue<String> drop;
- List<String> messages = Arrays.asList(
- "Mares eat oats",
- "Does eat oats",
- "Little lambs eat ivy",
- "Wouldn't you eat ivy too?");
- public Producer(BlockingQueue<String> d) { this.drop = d; }
- public void run()
- {
- try
- {
- for (String s : messages)
- drop.put(s);
- drop.put("DONE");
- }
- catch (InterruptedException intEx)
- {
- System.out.println("Interrupted! " +
- "Last one out, turn out the lights!");
- }
- }
- }
- class Consumer
- implements Runnable
- {
- private BlockingQueue<String> drop;
- public Consumer(BlockingQueue<String> d) { this.drop = d; }
- public void run()
- {
- try
- {
- String msg = null;
- while (!((msg = drop.take()).equals("DONE")))
- System.out.println(msg);
- }
- catch (InterruptedException intEx)
- {
- System.out.println("Interrupted! " +
- "Last one out, turn out the lights!");
- }
- }
- }
- public class ABQApp
- {
- public static void main(String[] args)
- {
- BlockingQueue<String> drop = new ArrayBlockingQueue(1, true);
- (new Thread(new Producer(drop))).start();
- (new Thread(new Consumer(drop))).start();
- }
- }
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/683090,如需转载请自行联系原作者