组成介绍
种类分析
jdk提供了7个阻塞队列 分别是
ArrayBlockingQueue :由数组结构组成的有界阻塞队列
LinkedBlockingQueue :一个由链表结构组成的有界(这个界的默认值是 Integer.MAX_VALUE)阻塞队列(可以看成是无界阻塞队列)
PriorityBlockingQueue :一个支持优先级排序的无界阻塞队列
DelayQueue:一个使用优先级队列实现的无界阻塞队列
SynchronousQueue:一个不存储元素的阻塞队列(单个元素的队列)
LinkedTransferQueue:一个由链表结构组成的无界阻塞队列
LinkedBlockingDeque:一个由链表结构组成的双向阻塞队列
常用方法
我们这里来重点看一下第三组方法 put和take 这里我们以ArrayBlockingQueue为例子
package com.zyk;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Demo {
public static void main(String[] args) throws InterruptedException {
//我们设置了默认大小是3 所以第四个会放不进去
BlockingQueue<String> blockingQueue=new ArrayBlockingQueue<>(3);
blockingQueue.put("a");
blockingQueue.put("a");
blockingQueue.put("a");
System.out.println("==============");
blockingQueue.put("a");
}
}
package com.zyk;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Demo {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.put("a");
blockingQueue.put("a");
blockingQueue.put("a");
blockingQueue.take();
blockingQueue.take();
blockingQueue.take();
blockingQueue.take();
}
}
我们来看这个put给我们的感受 我们这个队列就只有3个大小 我第4个put就非要放进去 放不进去我就不走 就一直等着 同样take也是 我取不到东西我就一直等着
SynchronousQueue演示
SynchronousQueue的特点是队列中只存放一个元素 put一个就必须take一个
如果put了一个 此时我们没有take出去 呢么第二个元素就put不进来
就好比一个匠人 一年只生产一块定制手表 生产一个 买走一个 生产一个 买走一个 不会一下生产两个
package com.zyk;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class Demo {
public static void main(String[] args) {
BlockingQueue blockingQueue=new SynchronousQueue();
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t put进去1");
try { blockingQueue.put(1); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+"\t put进去2");
try { blockingQueue.put(2); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+"\t put进去3");
try { blockingQueue.put(3); } catch (InterruptedException e) { e.printStackTrace(); }
},"aaa").start();
new Thread(()->{
try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
try { System.out.println(Thread.currentThread().getName()+"\t"+blockingQueue.take()); } catch (InterruptedException e) { e.printStackTrace(); }
try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
try { System.out.println(Thread.currentThread().getName()+"\t"+blockingQueue.take()); } catch (InterruptedException e) { e.printStackTrace(); }
try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
try { System.out.println(Thread.currentThread().getName()+"\t"+blockingQueue.take()); } catch (InterruptedException e) { e.printStackTrace(); }
},"bbb").start();
}
}