tryAcquire 用法
- 嘗試獲取一個許可,參數有:許可數,等待時間,時間單位。
- 表示:在規定時間內等待,超過時間則拋棄。
package com.mmall.concurrency.example.aqs;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
@Slf4j
public class SemaphoreExample3 {
private final static int threadCount = 20;
public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < threadCount; i++) {
final int threadNum = i;
exec.execute(() -> {
try {
if (semaphore.tryAcquire()) { // 嘗試獲取一個許可
test(threadNum);
semaphore.release(); // 釋放一個許可
}
} catch (Exception e) {
log.error("exception", e);
}
});
}
exec.shutdown();
}
private static void test(int threadNum) throws Exception {
log.info("{}", threadNum);
Thread.sleep(1000);
}
}
// 輸出
0
2
1
分析
- 之前一直以爲 acquire 是規定時間內,如果沒獲取到的就丟棄了,其實還是太年輕了,並不是這樣的。
- acquire 在上一篇講解到,如果阻塞住,就一直程序還是在跑的,而這個 tryAcquire 是真的規定時間內,沒獲取到的就丟棄了。
- 所以你會發現上面才輸出 3 條。