Skip to content

Commit 9f66ae8

Browse files
committed
[docs update]完善Java 并发常见面试题总结(下)的内容
1 parent 696b6d6 commit 9f66ae8

File tree

3 files changed

+440
-396
lines changed

3 files changed

+440
-396
lines changed

docs/java/concurrent/aqs.md

+15-2
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,20 @@ protected boolean isHeldExclusively()
114114

115115
#### 介绍
116116

117-
`synchronized``ReentrantLock` 都是一次只允许一个线程访问某个资源,`Semaphore`(信号量)可以指定多个线程同时访问某个资源。
117+
`synchronized``ReentrantLock` 都是一次只允许一个线程访问某个资源,而`Semaphore`(信号量)可以用来控制同时访问特定资源的线程数量。
118+
119+
Semaphore 的使用简单,我们这里假设有 N(N>5) 个线程来获取 `Semaphore` 中的共享资源,下面的代码表示同一时刻 N 个线程中只有 5 个线程能获取到共享资源,其他线程都会阻塞,只有获取到贡献资源的线程才能执行。等到有线程释放了共享资源,其他阻塞的线程才能获取到。
120+
121+
```java 
122+
// 初始共享资源数量
123+
final Semaphore semaphore = new Semaphore(5);
124+
// 获取1个许可
125+
semaphore.acquire();
126+
// 释放1个许可
127+
semaphore.release();
128+
```
129+
130+
当初始的资源个数为 1 的时候,`Semaphore` 退化为排他锁。
118131

119132
`Semaphore` 有两种模式:。
120133

@@ -199,7 +212,7 @@ public class SemaphoreExample1 {
199212
public static void main(String[] args) throws InterruptedException {
200213
// 创建一个具有固定线程数量的线程池对象(如果这里线程池的线程数量给太少的话你会发现执行的很慢)
201214
ExecutorService threadPool = Executors.newFixedThreadPool(300);
202-
// 一次只能允许执行的线程数量。
215+
// 初始许可证数量
203216
final Semaphore semaphore = new Semaphore(20);
204217

205218
for (int i = 0; i < threadCount; i++) {

0 commit comments

Comments
 (0)