Semaphore
信號量可以控制線程的并發(fā)數(shù)量
通常用于那些資源有明確訪問數(shù)量限制的場景,常用于限流 。
使用 Semaphore
先調(diào)用acquire()
獲取,然后通過try ... finally
保證在finally
中釋放。
Semaphore常用方法說明
-
acquire()
獲取一個令牌,在獲取到令牌、或者被其他線程調(diào)用中斷之前線程一直處于阻塞狀態(tài)。 -
acquire(int permits)
獲取一個令牌,在獲取到令牌、或者被其他線程調(diào)用中斷、或超時之前線程一直處于阻塞狀態(tài)。 -
acquireUninterruptibly()
獲取一個令牌,在獲取到令牌之前線程一直處于阻塞狀態(tài)(忽略中斷)。 -
tryAcquire()
嘗試獲得令牌,返回獲取令牌成功或失敗,不阻塞線程。 -
tryAcquire(long timeout, TimeUnit unit)
嘗試獲得令牌,在超時時間內(nèi)循環(huán)嘗試獲取,直到嘗試獲取成功或超時返回,不阻塞線程。
? -
release()
釋放一個令牌,喚醒一個獲取令牌不成功的阻塞線程。文章來源:http://www.zghlxwxcb.cn/news/detail-523942.html
面試??碱}目交替打印ABC
@Test
public void testSemaphore() {
int i1 = 100;
Semaphore semaphore1 = new Semaphore(1, true);
Semaphore semaphore2 = new Semaphore(0);
Semaphore semaphore3 = new Semaphore(0);
new Thread(() -> {
try {
for (int i = 0; i < i1; i++) {
semaphore1.acquire();
System.out.print("A");
semaphore2.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
for (int i = 0; i < i1; i++) {
semaphore2.acquire();
System.out.print("B");
semaphore3.release(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
for (int i = 0; i < i1; i++) {
semaphore3.acquire();
System.out.println("C");
semaphore1.release(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
Semaphore 使用及原理
文章來源地址http://www.zghlxwxcb.cn/news/detail-523942.html
到了這里,關(guān)于Java并發(fā)編程:Semaphore的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!