Java的Semaphore信號(hào)量使用及原理解讀
概述
Semaphore(信號(hào)量)是Java中一個(gè)并發(fā)控制工具,用于控制對(duì)共享資源的訪問。它基于計(jì)數(shù)器的原理,可以限制同時(shí)訪問某個(gè)資源的線程數(shù)量。
在Java中使用Semaphore,你需要按照以下步驟進(jìn)行操作:
導(dǎo)包:
import java.util.concurrent.Semaphore;
創(chuàng)建Semaphore對(duì)象:
Semaphore semaphore = new Semaphore(n);
其中,n是允許同時(shí)訪問共享資源的線程數(shù)量。
在需要訪問共享資源的代碼段前后,使用acquire()和release()方法來獲取和釋放信號(hào)量:
try {
semaphore.acquire(); // 獲取信號(hào)量,如果沒有可用的許可證,線程將被阻塞
// 訪問共享資源的代碼
} catch (InterruptedException e) {
// 處理中斷異常
} finally {
semaphore.release(); // 釋放信號(hào)量,增加一個(gè)許可證
}acquire()方法嘗試獲取一個(gè)許可證,如果當(dāng)前沒有可用的許可證,則該線程將被阻塞,直到有可用的許可證為止。release()方法釋放一個(gè)許可證,使其可供其他線程使用。
通過適當(dāng)?shù)厥褂胊cquire()和release()方法,在超過信號(hào)量允許的線程數(shù)量時(shí),可以限制并發(fā)訪問共享資源的線程數(shù)量,實(shí)現(xiàn)線程間的同步和互斥。
需要注意的是,Semaphore還提供了一些其他方法,如availablePermits()用于獲取當(dāng)前可用的許可證數(shù)量,以及tryAcquire()方法在不阻塞線程的情況下嘗試獲取許可證等。
具體例子
public static void main(String[] args) {
// 1. 創(chuàng)建 semaphore 對(duì)象
Semaphore semaphore = new Semaphore(3);
// 2. 10個(gè)線程同時(shí)運(yùn)行
for (int i = 0; i < 10; i++) {
new Thread(() -> {
// 3. 獲取許可
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
log.debug("running...");
sleep(1);
log.debug("end...");
} finally {
// 4. 釋放許可
semaphore.release();
}
}).start();
}
}07:35:15.485 c.TestSemaphore [Thread-2] - running...
07:35:15.485 c.TestSemaphore [Thread-1] - running...
07:35:15.485 c.TestSemaphore [Thread-0] - running...
07:35:16.490 c.TestSemaphore [Thread-2] - end...
07:35:16.490 c.TestSemaphore [Thread-0] - end...
07:35:16.490 c.TestSemaphore [Thread-1] - end...
07:35:16.490 c.TestSemaphore [Thread-3] - running...
07:35:16.490 c.TestSemaphore [Thread-5] - running...
07:35:16.490 c.TestSemaphore [Thread-4] - running...
07:35:17.490 c.TestSemaphore [Thread-5] - end...
07:35:17.490 c.TestSemaphore [Thread-4] - end...
07:35:17.490 c.TestSemaphore [Thread-3] - end...
07:35:17.490 c.TestSemaphore [Thread-6] - running...
07:35:17.490 c.TestSemaphore [Thread-7] - running...
07:35:17.490 c.TestSemaphore [Thread-9] - running...
07:35:18.491 c.TestSemaphore [Thread-6] - end...
07:35:18.491 c.TestSemaphore [Thread-7] - end...
07:35:18.491 c.TestSemaphore [Thread-9] - end...
07:35:18.491 c.TestSemaphore [Thread-8] - running...
07:35:19.492 c.TestSemaphore [Thread-8] - end...
源碼原理解析
加鎖解鎖流程原理
Semaphore 有點(diǎn)像一個(gè)停車場(chǎng),permits 就好像停車位數(shù)量,當(dāng)線程獲得了 permits 就像是獲得了停車位,然后 停車場(chǎng)顯示空余車位減一 剛開始,permits(state)為 3,這時(shí) 5 個(gè)線程來獲取資源

假設(shè)其中 Thread-1,Thread-2,Thread-4 cas 競(jìng)爭(zhēng)成功,而 Thread-0 和 Thread-3 競(jìng)爭(zhēng)失敗,進(jìn)入 AQS 隊(duì)列park 阻塞

接下來 Thread-0 競(jìng)爭(zhēng)成功,permits 再次設(shè)置為 0,設(shè)置自己為 head 節(jié)點(diǎn),斷開原來的 head 節(jié)點(diǎn),unpark 接 下來的 Thread-3 節(jié)點(diǎn),但由于 permits 是 0,因此 Thread-3 在嘗試不成功后再次進(jìn)入 park 狀態(tài)

源碼
構(gòu)造方法有倆個(gè):
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}創(chuàng)建 Semaphore 具有給定數(shù)量的許可和不公平公平設(shè)置。 參數(shù): 許可證 – 可用的許可證的初始數(shù)量。此值可能為負(fù)數(shù),在這種情況下,必須先進(jìn)行釋放,然后才能授予任何收購。
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}創(chuàng)建具有給定數(shù)量的許可和給定公平性設(shè)置的 。
Semaphore 參數(shù):
許可證 – 可用的許可證的初始數(shù)量。此值可能為負(fù)數(shù),在這種情況下,必須先進(jìn)行釋放,然后才能授予任何收購。
公平 – true 如果此信號(hào)量將保證在爭(zhēng)用中授予先進(jìn)先出的許可證,否則 false
static final class NonfairSync extends Sync {
private static final long serialVersionUID = -2694183684443567898L;
NonfairSync(int permits) {
// permits 即 state
super(permits);
}
// Semaphore 方法, 方便閱讀, 放在此處
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
// AQS 繼承過來的方法, 方便閱讀, 放在此處
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
// 嘗試獲得共享鎖
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
// Sync 繼承過來的方法, 方便閱讀, 放在此處
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
int available = getState();
int remaining = available - acquires;
if (
// 如果許可已經(jīng)用完, 返回負(fù)數(shù), 表示獲取失敗, 進(jìn)入 doAcquireSharedInterruptibly
remaining < 0 ||
// 如果 cas 重試成功, 返回正數(shù), 表示獲取成功
compareAndSetState(available, remaining)
) {
return remaining;
}
}
}
// AQS 繼承過來的方法, 方便閱讀, 放在此處
private void doAcquireSharedInterruptibly(int arg) throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
// 再次嘗試獲取許可
int r = tryAcquireShared(arg);
if (r >= 0) {
// 成功后本線程出隊(duì)(AQS), 所在 Node設(shè)置為 head
// 如果 head.waitStatus == Node.SIGNAL ==> 0 成功, 下一個(gè)節(jié)點(diǎn) unpark
// 如果 head.waitStatus == 0 ==> Node.PROPAGATE
// r 表示可用資源數(shù), 為 0 則不會(huì)繼續(xù)傳播
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
// 不成功, 設(shè)置上一個(gè)節(jié)點(diǎn) waitStatus = Node.SIGNAL, 下輪進(jìn)入 park 阻塞
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
// Semaphore 方法, 方便閱讀, 放在此處
public void release() {
sync.releaseShared(1);
}
// AQS 繼承過來的方法, 方便閱讀, 放在此處
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
// Sync 繼承過來的方法, 方便閱讀, 放在此處
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases;
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))
return true;
}
}
}到此這篇關(guān)于Java的Semaphore信號(hào)量使用及原理解讀的文章就介紹到這了,更多相關(guān)Semaphore信號(hào)量使用及原理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實(shí)現(xiàn)給屬性賦值的兩種方式
在Spring Boot中,配置文件是用來設(shè)置應(yīng)用程序的各種參數(shù)和操作模式的重要部分,Spring Boot支持兩種主要類型的配置文件:properties文件和YAML 文件,這兩種文件都可以用來定義相同的配置,接下來由小編給大家詳細(xì)的介紹一下這兩種方式2024-07-07
Spring啟動(dòng)過程中實(shí)例化部分代碼的分析之Bean的推斷構(gòu)造方法
這篇文章主要介紹了Spring啟動(dòng)過程中實(shí)例化部分代碼的分析之Bean的推斷構(gòu)造方法,實(shí)例化這一步便是在doCreateBean方法的?instanceWrapper?=?createBeanInstance(beanName,?mbd,?args);這段代碼中,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-09-09
淺談SpringBoot項(xiàng)目打成war和jar的區(qū)別
這篇文章主要介紹了淺談SpringBoot項(xiàng)目打成war和jar的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Spring中如何獲取request的方法匯總及其線程安全性分析
這篇文章主要給大家介紹了關(guān)于Spring中如何獲取request的方法匯總及其線程安全性分析的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-04-04
Java獲取e.printStackTrace()打印的信息方式
這篇文章主要介紹了Java獲取e.printStackTrace()打印的信息方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Java編程經(jīng)典小游戲設(shè)計(jì)-打磚塊小游戲源碼
這篇文章主要介紹了Java編程經(jīng)典小游戲設(shè)計(jì)-打磚塊小游戲源碼,還是挺不錯(cuò)的,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
一文詳解Java?Condition的await和signal等待通知機(jī)制
這篇文章主要為大家詳細(xì)介紹了Java?Condition的await和signal等待通知機(jī)制的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2025-02-02
SpringBoot的jar包如何啟動(dòng)的實(shí)現(xiàn)
本文主要介紹了SpringBoot的jar包如何啟動(dòng)的實(shí)現(xiàn),文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03

