亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解Java中的阻塞隊列

 更新時間:2021年06月16日 14:49:33   作者:小海子l  
在去年的面試過程中,被面試官問道“阻塞隊列”這個問題,因為當時并沒有對此問題進行深入理解,只是按照自己的理解說明了該問題,最后面試結果也不太好,今天對該問題進行簡要的面試并記錄如下;如有錯誤,歡迎指正,需要的朋友可以參考下

什么是阻塞隊列

在數(shù)據(jù)結構中,隊列遵循FIFO(先進先出)原則。在java中,Queue接口定義了定義了基本行為,由子類完成實現(xiàn),常見的隊列有ArrayDeque、LinkedList等,這些都是非線程安全的,在java 1.5中新增了阻塞隊列,當隊列滿時,添加元素的線程呈阻塞狀態(tài);當隊列為空時,獲取元素的線程呈阻塞狀態(tài)。

生產(chǎn)者、消費者模型

在這里插入圖片描述

生產(chǎn)者將元素添加到隊列中,消費中獲取數(shù)據(jù)后完成數(shù)據(jù)處理。兩者通過隊列解決了生產(chǎn)者和消費者的耦合關系;當生產(chǎn)者的生產(chǎn)速度與消費者的消費速度不一致時,可以通過大道緩沖的目的。

阻塞隊列的使用場景

線程池

在線程池中,當工作線程數(shù)大于等于corePoolSize時,后續(xù)的任務后添加到阻塞隊列中;

目前有那些阻塞隊列

在java中,BlockingQueue接口定義了阻塞隊列的行為,常用子類是ArrayBlockingQueueLinkedBlockingQueue

在這里插入圖片描述

BlockingQueue繼承了Queue接口,擁有其全部特性。在BlockingQueue的java doc中對其中的操作方法做了匯總

在這里插入圖片描述

插入元素

  • add(e):當隊列已滿時,再添加元素會拋出異常IllegalStateException
  • offer(e):添加成功,返回true,否則返回false
  • put:(e):當隊列已滿時,再添加元素會使線程變?yōu)樽枞麪顟B(tài)
  • offer(e, time,unit):當隊列已滿時,在末尾添加數(shù)據(jù),如果在指定時間內(nèi)沒有添加成功,返回false,反之是true

刪除元素

  •  remove(e):返回true表示已成功刪除,否則返回false
  • poll():如果隊列為空返回null,否則返回隊列中的第一個元素
  • take():獲取隊列中的第一個元素,如果隊列為空,獲取元素的線程變?yōu)樽枞麪顟B(tài)
  • poll(time, unit):當隊列為空時,線程被阻塞,如果超過指定時間,線程退出

檢查元素

  •  element():獲取隊頭元素,如果元素為null,拋出NoSuchElementException
  • peek():獲取隊頭元素,如果隊列為空返回null,否則返回目標元素

ArrayBlockingQueue

底層基于數(shù)組的有界阻塞隊列,在構造此隊列時必須指定容量;

構造函數(shù)

// 第一個	
public ArrayBlockingQueue(int capacity, boolean fair,Collection<? extends E> c) {
        this(capacity, fair);

        final ReentrantLock lock = this.lock;
        lock.lock(); // Lock only for visibility, not mutual exclusion
        try {
            int i = 0;
            try {
                for (E e : c) {
                    checkNotNull(e);
                    items[i++] = e;
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException();
            }
            count = i;
            putIndex = (i == capacity) ? 0 : i;
        } finally {
            lock.unlock();
        }
    }

	// 第二個
    public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }

	// 第三個
	public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }
  • capacity:隊列的初始容量
  • fair:線程訪問隊列的公平性。如果為true按照FIFO的原則處理,反之;默認為falsec:
  • 已有元素的集合,類型于合并兩個數(shù)組

put()方法

public void put(E e) throws InterruptedException {
         // 檢查元素是否為null
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        // 獲取鎖
        lock.lockInterruptibly();
        try {
            // 如果當前隊列為空,變?yōu)樽枞麪顟B(tài)
            while (count == items.length)
                notFull.await();
            // 反之,就添加元素
            enqueue(e);
        } finally {
            // 解鎖
            lock.unlock();
        }
    }

    private void enqueue(E x) {
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        // 此時隊列不為空,喚醒消費者
        notEmpty.signal();
    }

take()方法

 public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        // 獲取鎖
        lock.lockInterruptibly();
        try {
            // 如果隊列為空,消費者變?yōu)樽枞麪顟B(tài)
            while (count == 0)
                notEmpty.await();
            // 不為空,就獲取數(shù)據(jù)
            return dequeue();
        } finally {
            // 解鎖
            lock.unlock();
        }
    }

        private E dequeue() {
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        // 獲取隊頭元素x
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
         // 此時隊列沒有滿,同時生產(chǎn)者繼續(xù)添加數(shù)據(jù)
        notFull.signal();
        return x;
    }

LinkedBlockingQueue

底層基于單向鏈表的無界阻塞隊列,如果不指定初始容量,默認為Integer.MAX_VALUE,否則為指定容量

構造函數(shù)

// 不指定容量     
	public LinkedBlockingQueue() {
        this(Integer.MAX_VALUE);
    }
	// 指定容量
    public LinkedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        last = head = new Node<E>(null);
    }

	// 等同于合并數(shù)組
    public LinkedBlockingQueue(Collection<? extends E> c) {
        this(Integer.MAX_VALUE);
        final ReentrantLock putLock = this.putLock;
        putLock.lock(); // Never contended, but necessary for visibility
        try {
            int n = 0;
            for (E e : c) {
                if (e == null)
                    throw new NullPointerException();
                if (n == capacity)
                    throw new IllegalStateException("Queue full");
                enqueue(new Node<E>(e));
                ++n;
            }
            count.set(n);
        } finally {
            putLock.unlock();
        }
    }

put()方法

 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;
        // 獲取隊列中的數(shù)據(jù)量
        final AtomicInteger count = this.count;
        // 獲取鎖
        putLock.lockInterruptibly();
        try {
            // 隊列滿了,變?yōu)樽枞麪顟B(tài)
            while (count.get() == capacity) {
                notFull.await();
            }
            // 將目標元素添加到鏈表的尾端
            enqueue(node);
            // 總數(shù)增加
            c = count.getAndIncrement();
            // 隊列還沒有滿,繼續(xù)添加元素
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            // 解鎖
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
    }

take()方法

public E take() throws InterruptedException {
        E x;
        int c = -1;
        // 獲取隊列中的工作數(shù)
        final AtomicInteger count = this.count;
        final ReentrantLock takeLock = this.takeLock;
        // 獲取鎖
        takeLock.lockInterruptibly();
        try {
            // 如果隊列為空,變?yōu)樽枞麪顟B(tài)
            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;
    }

對比

相同點

  • 兩者都是通過Condition通知生產(chǎn)者和消費者完成元素的添加和獲取
  • 都可以指定容量

不同點

  •  ArrayBlockingQueue基于數(shù)據(jù),LinkedBlockingQueue基于鏈表
  • ArrayBlockingQueue內(nèi)有一把鎖,LinkedBlockingQueue內(nèi)有兩把鎖

在這里插入圖片描述
在這里插入圖片描述 

自己動手實現(xiàn)一個阻塞隊列

通過分析源碼可以知道,阻塞隊列其實是通過通知機制Condition完成生產(chǎn)者和消費的互通。也可以通過Object類中的wait()notify、notifyAll實現(xiàn)。下面是自己寫的一個阻塞隊列

public class BlockQueue {
    // 對象鎖
    public static final Object LOCK = new Object();
    // 控制變量的值 來通知雙方
    public boolean condition;
    
    public void put() {
        synchronized (LOCK) {
            while (condition) {
                try {
                    // 滿了
                    System.out.println("put   隊列滿了,開始阻塞");
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            condition = true;
            System.out.println("put   改為true,喚醒消費者");
            LOCK.notifyAll();
        }
    }


    public void take() {
        synchronized (LOCK) {
            while (!condition) {
                // 沒滿
                System.out.println("take   隊列沒滿,開始阻塞");
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            condition = false;
            System.out.println("take   改為false,喚醒生產(chǎn)者");
            LOCK.notifyAll();
        }
    }
}

參考文章:

并發(fā)容器之BlockingQueue (juejin.cn)

BlockingQueue (Java Platform SE 8 ) (oracle.com)

到此這篇關于詳解Java中的阻塞隊列的文章就介紹到這了,更多相關Java阻塞隊列內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論