- package kevin;
-
- import java.util.concurrent.ArrayBlockingQueue;
- import java.util.concurrent.BlockingQueue;
- import java.util.concurrent.TimeUnit;
-
-
-
-
-
-
- public class BlockingQueueDemo {
- public static void main(String[] args) {
- new BlockingQueueDemo().go();
- }
-
- private void go() {
-
-
- BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
- Thread t1 = new Thread(new Producer(queue, 500, "peak"));
-
-
- Thread t2 = new Thread(new Producer(queue, 1000, "nike"));
- Thread t3 = new Thread(new Customer(queue));
- t1.start();
- t2.start();
- t3.start();
- }
-
- private class Producer implements Runnable {
- private BlockingQueue<String> queue;
- private int timeout;
- private String category;
-
- public Producer(BlockingQueue<String> queue, int timeout,
- String category) {
- super();
- this.queue = queue;
- this.timeout = timeout;
- this.category = category;
- }
-
- @Override
- public void run() {
- while (!Thread.currentThread().isInterrupted()) {
- try {
-
-
- queue.put("product " + category);
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- }
- try {
- TimeUnit.MILLISECONDS.sleep(timeout);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- private class Customer implements Runnable {
- private BlockingQueue<String> queue;
-
- public Customer(BlockingQueue<String> queue) {
- super();
- this.queue = queue;
- }
-
- @Override
- public void run() {
- while (!Thread.currentThread().isInterrupted()) {
- try {
- System.out.println("product got:" + queue.take());
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- }
- try {
-
-
- TimeUnit.MILLISECONDS.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- }
-
- }
-
- }
有一点这里要说明 一下,其它 的在代码里我都 有简单的说明 了,这个demo比较简单,所以就不废话了。~~
NOTE:
因为BlockingQueue接口扩展了Queue接口,所以它从Queue接口那里得到了一些简单的队列操作方法
有个重载方法在使用的过程中应该注意。比如:offer(E)这个方法是从Queue那里得到的,它并不具有
阻塞性,而BlokingQueue提供的重载方法offer(E,long,TimeUnit)这个方法是一个阻塞方法,它具有
和put相似的功能,不过它提供了一个阻塞时间,时间过后如果还不能成功操作则放弃,返回false。
同样的问题在poll()和poll(long,TimeUnit)之间也存在,在使用的过程中请务必留意。
转载地址:http://blog.csdn.net/moreevan/article/details/6763508