BlockingQueue
| 方式 |
抛出异常 |
有返回值,不抛出异常 |
阻塞等待 |
超时等待 |
| 添加 |
boolean add(E e) |
boolean offer(E e) |
void put(E e) |
boolean offer(E e, long timeout, TimeUnit unit) |
| 移除 |
E remove() |
E poll() |
E take() |
E poll(long timeout, TimeUnit unit) |
| 检测队首元素 |
E element() |
E peek() |
- |
- |
/*
抛出异常
*/
public static void test1() {
// 参数:队列的大小
ArrayBlockingQueue
SynchronousQueue
/*
同步队列
和其他的BlockingQueue不一样,SynchronousQueue不存储元素
put了一个元素,必须从里面先take取出来,否则不能再put进去取!
*/
public class SynchronousQueueDemo {
public static void main(String[] args) {
BlockingQueue blockingQueue = new SynchronousQueue<>();//同步队列
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + " put 1");
blockingQueue.put("1");
System.out.println(Thread.currentThread().getName() + " put 2");
blockingQueue.put("2");
System.out.println(Thread.currentThread().getName() + " put 3");
blockingQueue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "T1").start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "T2").start();
}
}