JUC併發工具十一-阻塞隊列

目錄

1 ArrayBlockingQueue使用及原理

1.1 ArrayBlockingQueue使用

1.2 核心方法概覽

1.2.1 add和offer

1.2.2 帶有超時時間的offer方法

1.2.3 put方法

1.2.4 remove和poll方法

1.2.5 帶有超時的poll方法

1.2.6 take方法

2 LinkedBlockingQueue使用及原理

2.1 LinkedBlockingQueue的使用

2.2 核心方法概覽

2.2.1 add和offer

2.2.2 帶有超時時間的offer方法

2.2.3 put方法

2.2.4 remove和poll方法

2.2.5 帶有超時的poll方法

2.2.6 take方法

3 DelayQueue使用及原理

3.1 LinkedBlockingQueue的使用

3.2 核心方法概覽

3.2.1 PriorityQueue簡介

3.2.2 add、put和offer

3.2.3 take方法


隊列的基本使用在前面文章中已經講過,這裏再複習一下
add:將指定的元素插入到此隊列中(如果立即可行且不會違反容量限制),在成功時返回 true,如果當前沒有可用空間,則拋出 IllegalStateException。
offer:將指定元素插入到此隊列的尾部(如果立即可行且不會超出此隊列的容量),在成功時返回 true,如果此隊列已滿,則返回 false。可以指定超時時間
put:將指定元素插入到此隊列的尾部,如有必要,則等待空間變得可用。

remove:若隊列爲空,拋出NoSuchElementException異常。
poll:若隊列爲空,返回null。可以指定超時時間
take:若隊列爲空,發生阻塞,等待有元素。

1 ArrayBlockingQueue使用及原理

基於數組的有界阻塞隊列實現,在ArrayBlockingQueue內部,維護了一個定長數組,以便緩存隊列中的數據對象,這是一個常用的阻塞隊列,除了一個定長數組外,ArrayBlockingQueue內部還保存着兩個整形變量,分別標識着隊列的頭部和尾部在數組中的位置。 

1.1 ArrayBlockingQueue使用

@Test
public void testArrayBlockingQueue() throws InterruptedException {
    // 這裏創建一個容量爲5的阻塞隊列
    BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
    queue.put("a");
    queue.put("b");
    queue.put("c");
    queue.put("d");
    queue.put("e");
    new Thread(() ->{
        try {
            // 這裏會阻塞三秒
            Thread.sleep(3000L);
            queue.remove();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }).start();
    // 輸出false
    System.out.println(queue.offer("f", 1, TimeUnit.SECONDS));
    // 輸出true
    System.out.println(queue.offer("g", 5, TimeUnit.SECONDS));
    // 一直阻塞
    queue.put("h");
}

1.2 核心方法概覽

1.2.1 add和offer

add方法實際上是通過offer實現的,比較簡單不做贅述,這裏直接看offer方法代碼了

public boolean offer(E e) {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    // 加鎖
    lock.lock();
    try {
        if (count == items.length)
            // 如果隊列已滿直接返回false
            return false;
        else {
            // 如果不滿則入列,返回true
            enqueue(e);
            return true;
        }
    } finally {
        // 解鎖
        lock.unlock();
    }
}

private void enqueue(E x) {
    // assert lock.getHoldCount() == 1;
    // assert items[putIndex] == null;
    final Object[] items = this.items;
    // putIndex指向隊列尾部
    items[putIndex] = x;
    if (++putIndex == items.length)
        putIndex = 0;
    count++;
    // 喚醒別的等待線程
    notEmpty.signal();
}

1.2.2 帶有超時時間的offer方法

public boolean offer(E e, long timeout, TimeUnit unit)
    throws InterruptedException {

    checkNotNull(e);
    // 計算還有多長時間超時
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        // 如果隊列已滿則進入超時等待
        while (count == items.length) {
            if (nanos <= 0)
                // 如果已超時則返回false
                return false;
            nanos = notFull.awaitNanos(nanos);
        }
        // 入列
        enqueue(e);
        return true;
    } finally {
        lock.unlock();
    }
}

1.2.3 put方法

put方法和帶超時時間的offer方法差不多,只不過這裏等待是一直等待,不是超時等待

public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == items.length)
            notFull.await();
        enqueue(e);
    } finally {
        lock.unlock();
    }
}

1.2.4 remove和poll方法

remove方法也是通過poll方法實現的,這裏只看poll方法

public E poll() {
    final ReentrantLock lock = this.lock;
    // 加鎖
    lock.lock();
    try {
        // 如果有元素則彈出,如果沒有則返回空
        return (count == 0) ? null : dequeue();
    } finally {
        lock.unlock();
    }
}

private E dequeue() {
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    E x = (E) items[takeIndex];
    // takeindex指向隊列頭部
    items[takeIndex] = null;
    if (++takeIndex == items.length)
        takeIndex = 0;
    count--;
    if (itrs != null)
        itrs.elementDequeued();
    // 彈出元素後喚醒別的等待線程
    notFull.signal();
    return x;
}

1.2.5 帶有超時的poll方法

// 和帶有超時的offer方法類似,這裏不做過多講解

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    // 計算阻塞倒計時
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        // 如果隊列爲空進入超時等待
        while (count == 0) {
            if (nanos <= 0)
                return null;
            nanos = notEmpty.awaitNanos(nanos);
        }
        return dequeue();
    } finally {
        lock.unlock();
    }
}

1.2.6 take方法

take方法和帶超時時間的poll方法差不多,只不過這裏等待是一直等待,不是超時等待

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0)
            notEmpty.await();
        return dequeue();
    } finally {
        lock.unlock();
    }
}

2 LinkedBlockingQueue使用及原理

基於鏈表的有界阻塞隊列,內部維護者一個數據緩衝隊列,該隊列由一個鏈表組成, 採用添加移除兩個鎖高效的處理併發數據,從而實現添加元素和移除元素並行。

2.1 LinkedBlockingQueue的使用

使用比較簡單,只需要將引用的對象改成LinkedBlockingQueue創建的對象就行

@Test
public void testLinkedBlockingQueue() throws InterruptedException {
    // 這裏創建一個容量爲5的阻塞隊列
    BlockingQueue<String> queue = new LinkedBlockingQueue<>(5);
    queue.put("a");
    queue.put("b");
    queue.put("c");
    queue.put("d");
    queue.put("e");
    new Thread(() ->{
        try {
            // 這裏會阻塞三秒
            Thread.sleep(3000L);
            queue.remove();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }).start();
    // 輸出false
    System.out.println(queue.offer("f", 1, TimeUnit.SECONDS));
    // 輸出true
    System.out.println(queue.offer("g", 5, TimeUnit.SECONDS));
    // 一直阻塞
    queue.put("h");
}

2.2 核心方法概覽

2.2.1 add和offer

add方法實際上是通過offer實現的,比較簡單不做贅述,這裏直接看offer方法代碼了

public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final AtomicInteger count = this.count;
    // 如果容量已滿直接返回false
    if (count.get() == capacity)
        return false;
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    // 加鎖
    putLock.lock();
    try {
        // 如果容量不滿則元素入列
        if (count.get() < capacity) {
            enqueue(node);
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                // 如果隊列未滿則喚醒添加阻塞的線程
                notFull.signal();
        }
    } finally {
        // 釋放鎖
        putLock.unlock();
    }
    if (c == 0)
        // 如果原來容量爲0則喚醒移除阻塞的線程
        signalNotEmpty();
    return c >= 0;
}

// 入列方法比較簡單,把元素添加到末尾即可
private void enqueue(Node<E> node) {
    last = last.next = node;
}

2.2.2 帶有超時時間的offer方法

public boolean offer(E e, long timeout, TimeUnit unit)
    throws InterruptedException {

    if (e == null) throw new NullPointerException();
    // 計算還需要等待的時間
    long nanos = unit.toNanos(timeout);
    int c = -1;
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly();
    try {
        // 阻塞添加元素,直至超時
        while (count.get() == capacity) {
            if (nanos <= 0)
                return false;
            nanos = notFull.awaitNanos(nanos);
        }
        enqueue(new Node<E>(e));
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            // 如果隊列未滿則喚醒添加阻塞的線程
            notFull.signal();
    } finally {
        // 釋放鎖
        putLock.unlock();
    }
    if (c == 0)
        // 如果原來容量爲0則喚醒移除阻塞的線程
        signalNotEmpty();
    return true;
}

2.2.3 put方法

put方法和帶超時時間的offer方法差不多,只不過這裏等待是一直等待,不是超時等待

public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly();
    try {
        while (count.get() == capacity) {
            notFull.await();
        }
        enqueue(node);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
}

2.2.4 remove和poll方法

remove方法也是通過poll方法實現的,這裏只看poll方法

public E poll() {
    final AtomicInteger count = this.count;
    if (count.get() == 0)
        return null;
    E x = null;
    int c = -1;
    final ReentrantLock takeLock = this.takeLock;
    // 加take鎖
    takeLock.lock();
    try {
        if (count.get() > 0) {
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                // 如果還有元素則喚醒移除阻塞的線程
                notEmpty.signal();
        }
    } finally {
        // 釋放take鎖
        takeLock.unlock();
    }
    if (c == capacity)
        // 如果原來容量已滿則喚醒添加阻塞的線程
        signalNotFull();
    return x;
}
// 出列方法比較簡單,把元素first元素移除即可
private E dequeue() {
    Node<E> h = head;
    Node<E> first = h.next;
    h.next = h; // help GC
    head = first;
    E x = first.item;
    first.item = null;
    return x;
}

2.2.5 帶有超時的poll方法

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    E x = null;
    int c = -1;
    // 計算還需要等待的時間
    long nanos = unit.toNanos(timeout);
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    try {
        // 市場是移除元素,直至成功或超時
        while (count.get() == 0) {
            if (nanos <= 0)
                return null;
            nanos = notEmpty.awaitNanos(nanos);
        }
        // 出列
        x = dequeue();
        c = count.getAndDecrement();
        if (c > 1)
            // 如果還有元素則喚醒移除阻塞的線程
            notEmpty.signal();
    } finally {
        // 釋放take鎖
        takeLock.unlock();
    }
    if (c == capacity)
        // 如果原來容量已滿則喚醒添加阻塞的線程
        signalNotFull();
    return x;
}

2.2.6 take方法

take方法和帶超時時間的poll方法差不多,只不過這裏等待是一直等待,不是超時等待

public E take() throws InterruptedException {
    E x;
    int c = -1;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    try {
        while (count.get() == 0) {
            notEmpty.await();
        }
        x = dequeue();
        c = count.getAndDecrement();
        if (c > 1)
            notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
    if (c == capacity)
        signalNotFull();
    return x;
}

3 DelayQueue使用及原理

帶有延遲時間的無界隊列,其中元素只有當其指定的延遲時間到了才能夠從隊列中獲取該元素。該隊列應用場景很多,比如對緩存超時的對象移除、任務超時處理、空閒連接的關閉等等

3.1 LinkedBlockingQueue的使用

這裏我們用一個比較有趣的案例,日常生活中的網吧上網用延遲隊列來實現

/**
 * 定義一個網民類
 */
class InternetMan implements Delayed {
    private String name;
    //身份證
    private String id;
    //截止時間
    private Long endTime;
    //定義時間工具類
    private TimeUnit timeUnit = TimeUnit.SECONDS;

    public InternetMan(String name, String id, Long endTime) {
        super();
        this.name = name;
        this.id = id;
        this.endTime = endTime;
    }

    /**
     * 相互批較排序用
     */
    @Override
    public int compareTo(Delayed man) {
        return this.getDelay(this.timeUnit) - man.getDelay(this.timeUnit) > 0 ? 1:0;
    }

    /**
     * 用來判斷是否到了截止時間
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return endTime - System.currentTimeMillis();
    }

    @Override
    public String toString() {
        return "InternetMan [name=" + name + ", id=" + id + "]";
    }
}

/**
 * 定義一個網吧類
 */
class InternetBar implements Runnable {
    private DelayQueue<InternetMan> queue = new DelayQueue<>();

    public boolean yinye =true;

    public void up(String name, String id, int money){
        String time = DateUtil.datetimeToString(new Date());
        InternetMan man = new InternetMan(name, id, 1000 * money + System.currentTimeMillis());
        System.out.println("time:" + time + "," + man + "交錢" + money + "塊,開始上機...");
        this.queue.add(man);
    }

    public void down(InternetMan man){
        String time = DateUtil.datetimeToString(new Date());
        System.out.println("time:" + time + "," + man + "時間到下機...");
    }

    @Override
    public void run() {
        while(yinye){
            try {
                // 每秒鐘檢查一次
                TimeUnit.SECONDS.sleep(1L);
                InternetMan man = queue.take();
                down(man);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

測試代碼:

@Test
public void testDelayQueue() throws InterruptedException {
    try{
        System.out.println("網吧開始營業");
        InternetBar bar = new InternetBar();
        new Thread(bar).start();

        bar.up("zhangsan", "1", 1);
        bar.up("lisi", "2", 10);
        bar.up("wanger", "3", 5);
    }
    catch(Exception e){
        e.printStackTrace();
    }
    TimeUnit.MINUTES.sleep(1);
}

輸出:
網吧開始營業
time:2020-06-30 21:18:18,InternetMan [name=zhangsan, id=1]交錢1塊,開始上機...
time:2020-06-30 21:18:18,InternetMan [name=lisi, id=2]交錢10塊,開始上機...
time:2020-06-30 21:18:18,InternetMan [name=wanger, id=3]交錢5塊,開始上機...
time:2020-06-30 21:18:19,InternetMan [name=zhangsan, id=1]時間到下機...
time:2020-06-30 21:18:23,InternetMan [name=wanger, id=3]時間到下機...
time:2020-06-30 21:18:28,InternetMan [name=lisi, id=2]時間到下機...

3.2 核心方法概覽

3.2.1 PriorityQueue簡介

DelayQueue內部維護了一個PriorityQueue,該隊列對實現Comparable的元素進行排序。排序規則越小,越先取出來。源碼也比較簡單,有興趣的同學可以閱讀下源碼

3.2.2 add、put和offer

add和put方法都是調的offer方法

public boolean offer(E e) {
    final ReentrantLock lock = this.lock;
    // 加鎖
    lock.lock();
    try {
        // 添加元素
        q.offer(e);
        if (q.peek() == e) {
            leader = null;
            // 喚醒取元素的線程
            available.signal();
        }
        return true;
    } finally {
        lock.unlock();
    }
}

3.2.3 take方法

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    // 加鎖
    lock.lockInterruptibly();
    try {
        for (;;) {
            // 獲取第一個元素,如果爲空則阻塞等待
            E first = q.peek();
            if (first == null)
                available.await();
            else {
                // 獲取取出元素的等待時間
                long delay = first.getDelay(NANOSECONDS);
                if (delay <= 0)
                    // 如果等待時間<=0則直接取出
                    return q.poll();
                first = null;
                if (leader != null)
                    // 如果當前線程不爲空則等待
                    available.await();
                else {
                    // 如果當前線程爲空則進行超時等待
                    Thread thisThread = Thread.currentThread();
                    leader = thisThread;
                    try {
                        available.awaitNanos(delay);
                    } finally {
                        if (leader == thisThread)
                            leader = null;
                    }
                }
            }
        }
    } finally {
        if (leader == null && q.peek() != null)
            // 如果當前沒有佔用線程並且有元素則喚醒取元素的線程
            available.signal();
        // 釋放鎖
        lock.unlock();
    }
}


別的方法都比較簡單,這裏不做太多介紹

常用的阻塞隊列還有PriorityBlockingQueue、SynchronousQueue等,後續再更新
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章