Semaphore最詳細解析

2022-01-09 23:27:02 字數 1803 閱讀 8557

官方解釋:

我記得考科目一的時候有乙個大教室,這個教室只能同時允許兩百人考試,當有乙個考完之後,下乙個才能進去進行考試。門口會有安檢人員進行安檢,這個semaphore就相當於這個安檢員。

也可以理解為停車場,停車場內的停車位是固定的,只有當一輛或多輛車開走之後外面等待的車才能進去停車。

用法:

1、定義三個資格 

semaphore semaphore = new semaphore(3);

threadpoolexecutor poolexecutor =

new threadpoolexecutor(10, 20,

5000, timeunit.milliseconds,

new linkedblockingdeque<>(100));

for (int i = 0; i < 10; i++) catch (interruptedexception e)

}});

}poolexecutor.shutdown();

執行結果如下:(同一時刻只能執行三個執行緒。有點模糊,湊合看)

解析:一、定義:

public semaphore(int permits)
semaphroe底層也是用sync類,預設是非公平的,也有公平的構造方法。

public semaphore(int permits, boolean fair)
定義的資格數其實是設定鎖的狀態值的(aqs之前已說過,維護鎖狀態值和執行緒等待佇列)

abstract static class sync extends abstractqueuedsynchronizer 

}

二、為什麼能限制同時執行的執行緒數量呢?

這就是acquire方法的用處了

public void acquire(int permits)
點進acquiresharedinterruptibly這個方法看看:

public final void acquiresharedinterruptibly(int arg)

可以看到,跟之前countdownlatch的await方法是一樣的。

tryacquireshared方法最終執行的如下方法:

final int nonfairtryacquireshared(int acquires) 

}

上述是非公平的,公平的只加了乙個判斷執行緒等待佇列前是否有其它執行緒。排隊乙個乙個來。

static final class fairsync extends sync }}

}

這個就是為什麼semaphore能控制當前併發執行緒的數量的原因。

三、釋放鎖

執行緒獲取執行資格之後需要釋放鎖。這就是release方法的用處。不釋放的話鎖會一直被占用,其他執行緒就無法執行。

public void release(int permits)
點進releaseshared看看

public final boolean releaseshared(int arg) 

return false;

}

跟之前的countdownlatch是一樣的,只是實現不一樣。semaphore實現如下:

protected final boolean tryreleaseshared(int releases) 

}

我是liusy,乙個喜歡健身的程式設計師。

Semaphore 原始碼解析

semaphore 訊號量 從概念上講,訊號量維護一套許可。每次 acquire 方法呼叫都會根據需要進行阻塞,直到獲得許可為止,然後將其占用。每次 release 方法呼叫都會新增乙個許可,可能會喚醒因沒有獲取到許可而阻塞的執行緒。semaphore 基於 aqs 實現,不熟悉 aqs 的同學可以...

Semaphore原始碼解析

public semaphore int permits public semaphore int permits,boolean fair permits 獲取許可的數量 fair 有公平和非公平 abstract static class sync extends abstractqueueds...

原始碼解析 Semaphore

建立 semaphore 例項的時候,需要乙個引數 permits,這個基本上可以確定是設定給 aqs 的 state 的,然後每個執行緒呼叫 acquire 的時候,執行 state state 1,release 的時候執行 state state 1,當然,acquire 的時候,如果 sta...