一:常见阻塞队列
ArrayBlockingQueue 实现基于数组 ,使用时 必须指明大小
LinkedBlockingQueue 实现基于链表 ,默认大小为 Integer.MAX_VALUE
PriorityBlockingQueue 实现基于优先队列 可以无限大
DelayQueue 基于 优先队列,一种延时队列,只有当指定的时间到了,才可以从队列中获取元素
二:常用的方法
非阻塞队列
add 添加失败 会抛出异常
remove 删除失败,跑出异常
offer 添加失败,返回 false
poll 删除失败,返回 null
peek
建议使用 offer 和poll阻塞队列
take 如果空,则等待
put 如果 满 ,则等待
offer(E e,time) 超出 time 则执行失败 返回 false
pull (time) null
三:使用 Object.wait Object.notify 实现 生产者消费者模式
package concurrent;
import java.util.PriorityQueue;
import java.util.concurrent.ArrayBlockingQueue;
/*
* @author: wjf
* @version: 2016年3月30日 下午12:45:16
*/
public class TestArrayBlockingQueue {
private static PriorityQueue<Integer> queue=new PriorityQueue<Integer>();
private static int queuesize=10;
public static void main(String[] args){
// ArrayBlockingQueue<Integer> blockqueue=new ArrayBlockingQueue<Integer>(1);
Producer p=new Producer(TestArrayBlockingQueue.queue,TestArrayBlockingQueue.queuesize);
Consumer c=new Consumer(TestArrayBlockingQueue.queue,TestArrayBlockingQueue.queuesize);
p.start();
c.start();
}
}
class Producer extends Thread{
private PriorityQueue<Integer> queue;
private int size;
public Producer(PriorityQueue<Integer> queue,int size){
this.queue=queue;
this.size=size;
}
public void run(){
produce();
}
private void produce(){
while(true){
synchronized(queue){
if(queue.size()==size){
System.out.println("the queue is full,pleast wait");
try{
queue.wait();
}catch(InterruptedException e){
e.printStackTrace();
queue.notify();
}
}
else{
queue.offer(new Integer(1));
queue.notify();
System.out.println("produce a new item,the left size is: "+(size-queue.size()));
}
}
}
}
}
class Consumer extends Thread{
private PriorityQueue<Integer> queue;
private int size;
public Consumer(PriorityQueue<Integer> queue,int size){
this.queue=queue;
this.size=size;
}
public void run(){
consum();
}
private void consum(){
while(true){
synchronized(queue){
if(queue.size()==0){
System.out.println("the queue is empty,pleast wait");
try{
queue.wait();
}catch(InterruptedException e){
e.printStackTrace();
queue.notify();
}
}
else{
queue.poll();
queue.notify();
System.out.println("consume an item,the left size is: "+(size-queue.size()));
}
}
// 适用 BlockingQueue 内部已经实现了 线程间的通信机制
// try{
// queue.take();
// }catch(InterruptedException e){
// e.printStackTrace();
// }
}
}
}
使用ArrayBlockingQueue 实现的生产者消费者模式 更加的简介,如上面的代码所示,只需要take,put 内部判断满不满 ,以及内部实现线程间通信机制