java的各个队列之间的联系和区别是什么

java的各个并发队列之间的联系和区别

java.util.concurrent是在并发编程中很常用的实用工具类

ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue

 

下面是代码例子

/**
 * 
 */
package concurrent;

import java.util.Random;
import java.util.concurrent.BlockingQueue;

/**
 * @author think
 *
 */
class Producer implements Runnable {
    private final BlockingQueue<Integer> queue;

    Producer(BlockingQueue<Integer> q) {
        queue = q;
    }

    public void run() {
        try {
            while (true) {
                queue.put(produce());
            }
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }

    Integer produce() {
        Random random = new Random();
        return random.nextInt();
    }
}

 

/**
 * 
 */
package concurrent;

import java.util.concurrent.BlockingQueue;

/**
 * @author think
 *
 */
class Consumer implements Runnable {
    private final BlockingQueue<Integer> queue;

    Consumer(BlockingQueue<Integer> q) {
        queue = q;
    }

    public void run() {
        try {
            while (true) {
                consume(queue.take());
            }
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }

    void consume(Integer x) {
        System.out.println(x);
    }
}

 

/**
 * 
 */
package concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author think
 *
 */
class Setup {
    public static void main(String[] args) {
        BlockingQueue<Integer> q = new ArrayBlockingQueue<Integer>(100);
        Producer p = new Producer(q);
        Consumer c1 = new Consumer(q);
        Consumer c2 = new Consumer(q);
        new Thread(p).start();
        new Thread(c1).start();
        new Thread(c2).start();
    }
}

 

 

 

ArrayBlockingQueue 一个由数组支持的有界阻塞队列

DelayQueue Delayed 元素的一个无界阻塞队列,只有在延迟期满时才能从中提取元素

LinkedBlockingDeque 一个基于已链接节点的、任选范围的阻塞双端队列。 

LinkedBlockingQueue 一个基于已链接节点的、范围任意的 blocking queue

PriorityBlockingQueue 一个无界阻塞队列,它使用与类 PriorityQueue 相同的顺序规则,并且提供了阻塞获取操作。

SynchronousQueue 一种阻塞队列,其中每个插入操作必须等待另一个线程的对应移除操作 ,反之亦然。

 

Java线程:新特征-阻塞栈LinkedBlockingDeque 

http://lavasoft.blog.51cto.com/62575/222530/

 

 

http://www.cnblogs.com/jackyuj/archive/2010/11/24/1886553.html

 

PriorityBlockingQueue

http://vakinge.iteye.com/blog/625613

http://blog.csdn.net/xin_jmail/article/details/26157971

http://zzhonghe.iteye.com/blog/826757

posted @ 2015-02-06 15:45  唾手可得的树  阅读(340)  评论(0编辑  收藏  举报