阻塞队列,顾名思义,首先是一个队列,而阻塞队列在数据结构中所起的作用是:
线程1向队列添加元素,线程2从队列取元素。
当阻塞队列是空时,从队列取元素的操作会被阻塞。
当阻塞队列满时,向队列添加元素的操作会被阻塞。
试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列插入新的元素。
同样,试图往已满的阻塞队列中添加元素的线程也会被阻塞,直到其他线程从队列中移除一个或者多个元素或者完全清空队列后使队列重新变得空闲起来并后续新增。
在多线程领域:所谓阻塞,在某些情况下会挂起线程(即阻塞),一旦条件满足,被挂起的线程又会自动被唤醒。
为什么需要BlockingQueue?
好处是不需要关心什么时候需要阻塞线程,什么时候需要唤醒线程,因为这一切BlockingQueue都给包办了。
常用种类
- ArrayBlockingQueue:由数组结构组成的有界阻塞队列。
- LinkedBlockingQueue:由链表结构组成的有界(但大小默认是Integer.MAX_VALUE)阻塞队列。
- PriorityBlockingQueue:支持优先级排序的无界阻塞队列。
- DelayQueue:使用优先级队列实现的延迟无界阻塞队列。
- SynchronousQueue:不存储元素的阻塞队列,也即单个元素的队列。
- LinkedTransferQueue:有链表结构组成的无界阻塞队列。
- LinkedBlockingDeque:由链表结构组成的双向阻塞队列。
方法介绍
抛出异常 | 当阻塞队列满时,再往队列里add插入元素会抛出IllegalStateException:Queue full;当阻塞队列空时,再往队列remove移除元素会抛出NoSuchElementException |
---|---|
特殊值 | 插入方法,成功true,失败false;移除方法,成功返回出队列的元素,队列里没有就返回null |
阻塞 | 当阻塞队列满时,生产者线程继续往队列里put元素,队列会一直阻塞生产线程直到队列不满;当阻塞队列为空时,消费者线程试图从队列里take元素,队列会一直阻塞消费者线程直到队列有元素。 |
超时 | 队列满,添加元素的线程会阻塞一段时间后停止。队列空,移除元素的线程会阻塞一段时间后停止。 |
案例
抛出异常
add
package juc;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
//此时队列满,再次添加时会抛IllegalStateException
System.out.println(blockingQueue.add("x"));
}
}
remove
package juc;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//此时队列空,再次删除会抛NoSuchElementException
System.out.println(blockingQueue.remove());
}
}
特殊值
package juc;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("a"));
//插入失败返回false
System.out.println(blockingQueue.offer("x"));
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//取元素失败返回null
System.out.println(blockingQueue.poll());
}
}
阻塞
put
package juc;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.put("a");
blockingQueue.put("a");
blockingQueue.put("a");
System.out.println("=======");
//满了继续插入会阻塞
blockingQueue.put("x");
}
}
take
package juc;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueDemo {
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();
System.out.println("=======");
//空了再取会阻塞
blockingQueue.take();
}
}
超时
package juc;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
//满了阻塞两秒钟后,如果还是满的返回false
System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
}
}
SynchronousQueue
单个元素的阻塞队列。也就是说,队列中如果有一个元素,就不会继续往队列添加。
案例
package juc;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class SynchronousBlockingDemo {
public static void main(String[] args) {
BlockingQueue<String> objects = new SynchronousQueue<>();
//如果是其他的阻塞队列,会连续put,但是SynchronousQueue只会放入一个,如果没有取就不会再次放入
new Thread(()->{
try{
System.out.println(Thread.currentThread().getName()+"\t put 1");
objects.put("1");
System.out.println(Thread.currentThread().getName()+"\t put 2");
objects.put("2");
System.out.println(Thread.currentThread().getName()+"\t put 3");
objects.put("3");
}catch (Exception e){
e.printStackTrace();
}
},"t1").start();
new Thread(()->{
try{
try{
TimeUnit.SECONDS.sleep(5);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"\t"+objects.take());
try{
TimeUnit.SECONDS.sleep(5);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"\t"+objects.take());
try{
TimeUnit.SECONDS.sleep(5);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"\t"+objects.take());
}catch (Exception e){
e.printStackTrace();
}
},"t2").start();
}
}
synchronized和lock的区别
原始组成
- synchronized是关键字,属于jvm层面,其底层通过monitor实现的,monitorenter表示进入,monitorexit表示离开。
- Lock是具体类,是api层面。
使用方法
- Synchronized不需要手动释放锁,当代码执行完后系统会自动让线程释放对锁的占用。
- ReentrantLock需要用户手动释放锁,若没有主动释放锁,就有可能导致死锁。需要Lock()和unLock()方法配合try/catch语句块完成。
等待是否可中断
- Synchronized不可中断,除非抛出异常或者正常运行完成。
- ReentrantLock可中断,设置超时方法tryLock(long timeout,TimeUnit unit);LockInterruptibly()放代码块中,调用interrupt()方法可中断。
加锁是否公平
- synchronized非公平锁。
- ReentrantLock默认是非公平锁,构造方法可传入boolean值,true为公平锁,false为非公平锁。
锁绑定多个条件Condition
- synchronized没有。
- ReentrantLock用来实现分组唤醒需要的线程,可以精确唤醒,而不是像synchronized要么随机唤醒一个线程要么唤醒全部线程。
package juc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 多线程之间按顺序调用,实现A->B->C三个线程启动:
* AA打印5次,BB打印10次,CC打印15次。。。。。来10轮。
*/
class ShareResource{
private int number = 1;
private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
public void print5(){
lock.lock();
try{
while (number!=1){
c1.await();
}
for (int i = 1; i <= 5 ; i++) {
System.out.println(Thread.currentThread().getName()+"\t "+number);
}
number = 2;
c2.signal();
} catch(Exception e){
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void print10(){
lock.lock();
try{
while (number!=2){
c2.await();
}
for (int i = 1; i <= 10 ; i++) {
System.out.println(Thread.currentThread().getName()+"\t "+number);
}
number = 3;
c3.signal();
} catch(Exception e){
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void print15(){
lock.lock();
try{
while (number!=3){
c3.await();
}
for (int i = 1; i <= 15 ; i++) {
System.out.println(Thread.currentThread().getName()+"\t "+number);
}
number = 1;
c1.signal();
} catch(Exception e){
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
public class SynchronizedReentrantDemo {
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
new Thread(()->{
for (int i = 1; i <= 10 ; i++) {
shareResource.print5();
}
},"AA").start();
new Thread(()->{
for (int i = 1; i <= 10 ; i++) {
shareResource.print10();
}
},"BB").start();
new Thread(()->{
for (int i = 1; i <= 10 ; i++) {
shareResource.print15();
}
},"CC").start();
}
}
阻塞队列用途:生产者消费者模式
传统版
package juc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//一个初始值为0的变量,两个线程对其交替操作,一个加1一个减1,来5轮。
public class ProdConsumer_TraditionDemo {
public static void main(String[] args) {
ShareData shareData = new ShareData();
new Thread(()->{
for (int i = 1; i <=5 ; i++) {
try {
shareData.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t1").start();
new Thread(()->{
for (int i = 1; i <=5 ; i++) {
try {
shareData.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t2").start();
}
}
class ShareData{
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
//加方法
public void increment() throws InterruptedException {
lock.lock();
try{
//如果当前线程的值不为0,不进行加操作,等待。
/**
* 防止虚假唤醒:在单参数版本中,中断和虚假唤醒是可能的,这种方法应该始终在循环中使用
* As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
*
* synchronized (obj) {
* while (<condition does not hold>)
* obj.wait();
* ... // Perform action appropriate to condition
* }
*/
while (number!=0){
//等待
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName()+"\t "+number);
condition.signalAll();
} catch(Exception e){
e.printStackTrace();
}finally{
lock.unlock();
}
}
//减方法
public void decrement() throws InterruptedException {
lock.lock();
try{
while (number==0){
//等待
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName()+"\t "+number);
condition.signalAll();
} catch(Exception e){
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
阻塞队列版
package juc;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class MyResource{
private volatile boolean flag = true; //默认开启,生产消费
private AtomicInteger atomicInteger = new AtomicInteger();
BlockingQueue<String> blockingQueue = null;
public MyResource(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
System.out.println(blockingQueue.getClass().getName());
}
public void myProd() throws Exception{
String data = null;
boolean retValue;
while (flag){
data = atomicInteger.incrementAndGet()+"";
retValue = blockingQueue.offer(data,2L, TimeUnit.SECONDS);
if(retValue){
System.out.println(Thread.currentThread().getName()+"\t 插入队列"+data+"成功");
}else{
System.out.println(Thread.currentThread().getName()+"\t 插入队列"+data+"失败");
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println(Thread.currentThread().getName()+"\t 生产结束");
}
public void myConsumer() throws Exception{
String result = null;
while (flag){
result = blockingQueue.poll(2L,TimeUnit.SECONDS);
if(result == null || result.equalsIgnoreCase("")){
flag = false;
System.out.println(Thread.currentThread().getName()+"\t 消费退出");
System.out.println();
System.out.println();
return;
}
System.out.println(Thread.currentThread().getName()+"\t 消费队列"+result+"成功");
}
}
public void stop(){
flag = false;
}
}
public class ProdConsumer_BlockQueueDemo {
public static void main(String[] args) {
MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t 生产线程启动");
try {
myResource.myProd();
} catch (Exception e) {
e.printStackTrace();
}
},"Prod").start();
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t 生产线程启动");
try {
myResource.myConsumer();
} catch (Exception e) {
e.printStackTrace();
}
},"Consumer").start();
try{
TimeUnit.SECONDS.sleep(5);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println();
System.out.println();
System.out.println();
System.out.println("5秒钟到,结束");
myResource.stop();
}
}