阻塞队列
阻塞队列
为什么需要BlockingQueue?
不需要关心什么时候阻塞线程,什么时候唤醒线程。
阻塞队列用在哪?
- 生产者消费者模式
- 线程池
- 消息中间件
BlockingQueue 的几个 API
![]()
SynchronousQueue
是什么?
SynchronousQueue 是 一个不存储元素的阻塞队列,也就是说,只有当一个线程put进去后,别的线程get出来后才能继续put。
public class BlockingQueue {
public static void main(String[] args) throws InterruptedException {
SynchronousQueue<Integer> synchronousQueue = new SynchronousQueue<>();
new Thread(()->{
try {
synchronousQueue.put(1);
System.out.println(Thread.currentThread().getName()+"\t添加元素"+1);
synchronousQueue.put(2);
System.out.println(Thread.currentThread().getName()+"\t添加元素"+2);
synchronousQueue.put(3);
System.out.println(Thread.currentThread().getName()+"\t添加元素"+3);
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t1").start();
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+"\t获取元素"+synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
//过三秒再获取元素
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println(Thread.currentThread().getName()+"\t获取元素"+synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
//过三秒再获取元素
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println(Thread.currentThread().getName()+"\t获取元素"+synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t2").start();
}
} 