阻塞队列

阻塞队列介绍

在这里插入图片描述

线程1往阻塞队列中添加元素,而线程2从阻塞队列中移除元素

当阻塞队列是空时,从队列中获取元素的操作将会被阻寒。
当阻塞队列是满时,往队列里添加元素的操作将会被阻塞。

试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列插入新的元素。
试图往己满的阻塞队列中添加新元素的线程同样也会被阻塞,直到其他的线程从列中移除一个或者多个元素或者完全清空队
列后使队列重新变得空闲起来并后续新增

为什么用?有什么好处?

在多线程领域:

​ 所谓阻塞,在某些情况下会挂起线程(即阻塞),- -旦条件满足,被挂起的线程又会自动被唤醒

为什么需要BlockingQueue

好处是我们不需要关心什么时候需要阻塞线程,什么时候需要唤醒线程,因为这一切BlockingQueue都给你一手包办了

在concurrent包发布以前,在多线程环境下,我们每个程序员都必须去自己控制这些细节,尤其还要兼顾效率和线程安全,而这会给我们的程序带来不小的复杂度。

架构介绍

阻塞类

ArrayBlockingQueue:由数组结构组成的有界阻塞队列。
在这里插入图片描述

LinkedBlockingQueue :由链表结构组成的有界(但大小默认值为Integer.MAX_VALUE)阻塞队列

 public LinkedBlockingDeque() {
        this(Integer.MAX_VALUE);
    }
 public LinkedBlockingDeque(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
    }
一般当作无界队列,因为Integer.MAX_VALUE的值为21亿 

PriorityBlockingQueue:支持优先级排序的无界阻塞队列。

DelayQueue:使用优先级队列实现的延迟无界阻塞队列。

SynchronousQueue:不存储元素的阻塞队列,也即单个元素的队列。

SynchronousQueue没有容量。
与其他BlockingQueue不同,SynchronousQueue是一个不存储元素的BlockingQuege。
每一个put操作必须要等待一个take操作,否则不能继续添加元素,反之亦然。 

LinkedTransferQueue:由链表结构组成的无界阻塞队列。

LinkedBlockingDeque:由 链表结构组成的双向阻塞队列

常用方法

方法类型抛出异常特殊值阻塞超时
插入add(e)offer(e)put(e)offer(e,time,unit)
移除remove()poll()take()poll(time,unit)
检查element()peek()不可用不可用

抛出异常

当阻塞队列满时,再往队列里add插入元素会抛llgalStateException: Queue full
当阻塞队列空时,再往队列里remove移除元累会抛NoSuchElementException

特殊值

插入方法,成功ture失败false
移除方法,成功返回出队列的元素,队列里面没有就返回null

一直阻塞

当阻塞队列满时,生产者线程继续往队列里put元素,队列会一直阻塞生产线程直到put数据or响应中断退出。
当阻塞队列空时,消费者线程试图从队列里take元素,队列会一直阻塞消费者线程直到队列可用。

超时退出

当阻塞队 列满时,队列会阻塞生产者线程一定时间, 超过后限时后生产者线程会退出

用在哪?

线程池 消息中间件

题目:一 个初始值为零的变量,两个线程对其交替操作,一 个加1一 个减1,来5轮

1线程 操作(方法) 资源类

2判断 干活 通知

3防止虑假唤醒机制

public class ProdConsumer_TraditionDemo {
    public static void main(String[] args) {
        shareDate shareDate = new shareDate();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                shareDate.increment();
            }
        },"AAA").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                shareDate.decrement();
            }
        },"BBB").start();
    }
}
class shareDate{
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    public void increment(){
        try {
            lock.lock();
            //判断
            while (number != 0){
                //等待
                condition.await();

            }
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //唤醒
            condition.signalAll();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void decrement(){
        try {
            lock.lock();
            while (number == 0 ){
                //等待
                condition.await();
            }
            number --;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}

synchronized和lock有什么区别?

1原始构成

synchronized是关键字属于JVM层面,

monitorenter(底层是通过monitor对象来完成,其实wait/notify 等方法也依赖monitor对象只有在同步块或方法中才能调wait/notify等方法
monitorexit会进行两次,一次正常退出一次异常退出,保证能退出

Lock是具体类(java. util. concurrent. locks . Lock)是api层面的锁

2使用方法

synchronized不需要用户去手动释放锁,当synchronized代码执行完后系统会自动让线程释放对锁的占用
ReentrantLock,则需要用户去手动释放锁若没有主动释放锁,就有可能导致出现死锁现象。
需要Lock()和lunlock()方法配合try/finally语句块来完成。

3等待是否可中断

synchronized不可中断,除非抛出异常或者正常运行完成
ReentrantLock可中断,设置超时方法tryLock(long timeout, TimeUnit unit)
					lockInterruptibly()放代码块中,调用interrupt() 方法可中断

4加锁是否公平

synchronized非公平锁
Reentrantlock两者都可以,默认非公平锁,构造方法可以传入boolean值, true为公平锁,false 为非公平锁

锁绑定多个条件condition

synchronized没有
ReentrantLock用来实现分组唤醒需要唤醒的线程们,可以精确唤醒,而不是像synchronized要么随机唤醒一个线程要么唤醒全部线程。

绑定多个条件condition实现精确唤醒

题目:多线程之间按顺序调用,实现A->B->C三 个线程启动,要求如下:
AA打印5次,BB打印10次, CC打印15次
紧接着
AA打印5次,BB打印10次, Cc打印15次
来10轮

package Thread.练习;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 肥蛋
 * 2021/1/3
 */
public class SyncAndReentrantLockDemo {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                shareResource.print5();
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                shareResource.print10();
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                shareResource.print15();
            }
        },"AA").start();
    }
}
class ShareResource{
    private volatile int flag = 1; //A:1 B:2 C:3
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void  print5(){
        try {
            lock.lock();
            //判断
            while (flag != 1){
                c1.await();
            }
            //干活
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + flag);
            }
            //唤醒
            flag = 2;
            c2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void  print10(){
        try {
            lock.lock();
            //判断
            while (flag != 2){
                c2.await();
            }
            //干活
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + flag);
            }
            //唤醒
            flag = 3;
            c3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void  print15(){
        try {
            lock.lock();
            //判断
            while (flag != 3){
                c3.await();
            }
            //干活
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + flag);
            }
            //唤醒
            flag = 1;
            c1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

整合

volatile/CAS/atomic Integer/BLockQueue/线程交互/原子引用

最多一次性生成3个,第4个生产了如果还没被取出,就会退出

package Thread.练习;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 肥蛋
 * 2021/1/3
 */
public class ProdConsumer_BlockQueueDemo {
    public static void main(String[] args) {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(3));
            new Thread(()->{
                System.out.println("生产线程启动");
                try {
                    myResource.prod();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"A").start();

            new Thread(()->{
                System.out.println("消费线程启动");
                try {
                    myResource.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"B").start();
 


        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        myResource.stop();
    }
}
class MyResource{
    private volatile boolean flag = true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }
    public void prod() throws InterruptedException {
        String date = null;
        boolean revalue;
        //判断
        while (flag){
            date = atomicInteger.incrementAndGet()+ "";
            revalue = blockingQueue.offer(date,2,TimeUnit.SECONDS);
            if (revalue){
                System.out.println(Thread.currentThread().getName() + "\t插入队列" + date + "成功");
            }else {
                System.out.println(Thread.currentThread().getName() + "\t插入队列" + date + "失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName() + "\t任务停止 flag=false");
    }
    public void consumer() throws InterruptedException {
        String revalue = null;
        while (flag){
            revalue = blockingQueue.poll(2, TimeUnit.SECONDS);
            if (revalue == null || revalue.equalsIgnoreCase("")){
                flag = false;
                System.out.println(Thread.currentThread().getName() + "\t取出队列" + revalue + "失败");
            }else {
                System.out.println(Thread.currentThread().getName() + "\t取出队列" + revalue + "成功");
            }
        }
    }
    public void stop(){
        flag = false;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值