各種并發(fā)類的使用場景
wait notify
他們兩個組合適用于比較簡單的場景,由于 nofity 并不能執(zhí)行喚醒的對象,就會導致如果喚醒了一個執(zhí)行時機不正確的情況,所以被喚醒的線程還需要判斷當前狀態(tài)是否適合自己執(zhí)行,如果不適合,就需要重新就行wait ,并通知其他線程, 在線程調(diào)度過程中會涉及到 線程的上下文切換,這也是一個比較消耗資源的操作,
他比較適合簡單的生產(chǎn)消費模式
雖然說wait notify 能實現(xiàn)生產(chǎn)消費模式,但是寫起來代碼量還是很多的, 如果使用ArrayBlockingQueue 的put 與 take方法,他們組合本身就是一個生產(chǎn)消費模式,使用過程中的代碼量非常少,
val queue=ArrayBlockingQueue<Int>(20)
thread {
for (i in 0..10000){
var i= queue.take()
Log.i("tian.shm","取出一個$i")
sleep(500)
}
}
thread {
for (i in 0..10000){
queue.put(i)
Log.i("tian.shm","添加一個")
sleep(250)
}
}
這里需要介紹一下BlockingQueue 的3組方法
add remove --> 不滿足當前情況就會拋出異常
put take --> 阻塞隊列
poll offer --> 返回執(zhí)行結(jié)果,如果沒執(zhí)行成功返回false
所以在線程池的隊列中,我們可以根據(jù)業(yè)務使用不同的策略來適配
ArrayBlockingQueue 的實現(xiàn)原理
ArrayBlockingQueue 是一個靜態(tài)數(shù)組,他有2把鎖, notEmptyLock notFullLock , put 與 take的實現(xiàn)方式如下
put
public void put(E e) throws InterruptedException {
Objects.requireNonNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
可以看到在put 的過程中是先拿到鎖,如果滿了就讓 notFull 等待,直到有位置后,加入隊列
而take方法的實現(xiàn)如下
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
就一個地方不一樣,那就是如果現(xiàn)在數(shù)據(jù)沒有為了,等待被喚醒
countdownlatch
一個非常好的計數(shù)條件, 他是基于 AQS 的 Shared 方案來實現(xiàn)的,即可以同時多個線程wait ,當計數(shù)器為0時,同時啟用多個等待的線程, countdownlatch 比較好的使用場景就是 android 的啟動任務優(yōu)化,如果某一個任務的啟動調(diào)試是前面的某些個任務,那么他的啟動時機就是前面所有的任務都啟動完成,在我的App 啟動任務優(yōu)化方案中使用的就是這個方法,大家可以看一下,我寫了非常多的注釋 https://github.com/tsm1991/StartUp
LinkedBlockingQueue
他是一個鏈表的阻塞隊列,在線程池中使用它由于capacity 這個參數(shù)設置的是 Integer.MAX_VALUE 就代表著所有的任務都可以進入到隊列中,并不會被拋棄,在 LinkedBlockingQueue 的設計當中,他的數(shù)據(jù)插入與 數(shù)據(jù)讀取使用的是2把鎖,2把鎖互不干擾,這個理解起來也比較好理解,在插入的過程中不應讀取,只會影響到后續(xù)的插入,反之亦然,但是在刪除節(jié)點的過程中的他調(diào)用了fulllock ,也就是將2個鎖都鎖起來了,就代表著,如果想要做數(shù)據(jù)的刪除操作時 就與 ArrayBlockingQueue 比較相似了,其他操作都不能做了,下面看一下他的 poll put remove
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
// Note: convention in all put/take/etc is to preset local var
// holding count negative to indicate failure unless set.
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
/*
* Note that count is used in wait guard even though it is
* not protected by lock. This works because count can
* only decrease at this point (all other puts are shut
* out by lock), and we (or some other waiting put) are
* signalled if it ever changes from capacity. Similarly
* for all other uses of count in other wait guards.
*/
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
由于我們介紹過 capacity 是 Integer.MAX_VALUE ,所以 notFull 與 notEmpty 的鎖就不介紹了,其實他的實現(xiàn)原理與 ArrayBlockingQueue 相類似的,這里注意使用的是 putLock
再來看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 <= 0L)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}
看一看到他使用的是 takeLock ,與插入數(shù)據(jù)不是同一把鎖,所以說他的插入與讀取是互不干擾的
但是到了remove 又是另一種情況了
public boolean remove(Object o) {
if (o == null) return false;
fullyLock();
try {
for (Node<E> trail = head, p = trail.next;
p != null;
trail = p, p = p.next) {
if (o.equals(p.item)) {
unlink(p, trail);
return true;
}
}
return false;
} finally {
fullyUnlock();
}
}
void fullyLock() {
putLock.lock();
takeLock.lock();
}
在刪除節(jié)點的過程中,使用的是fulllock,也就是2把鎖都鎖住了
LinkedBlockingDeque
他是一個鏈表組成的雙向阻塞隊列,由于他是雙向鏈表,并且讀寫鎖是分離的,能保證數(shù)據(jù)的有序性,常常用于視頻流的編解碼,相較于LinkedBlockingQueue 只能一邊插入與讀取,破壞了數(shù)據(jù)的順序,