File tree 3 files changed +440
-396
lines changed
3 files changed +440
-396
lines changed Original file line number Diff line number Diff line change @@ -114,7 +114,20 @@ protected boolean isHeldExclusively()
114
114
115
115
#### 介绍
116
116
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 ` 退化为排他锁。
118
131
119
132
` Semaphore ` 有两种模式:。
120
133
@@ -199,7 +212,7 @@ public class SemaphoreExample1 {
199
212
public static void main (String [] args ) throws InterruptedException {
200
213
// 创建一个具有固定线程数量的线程池对象(如果这里线程池的线程数量给太少的话你会发现执行的很慢)
201
214
ExecutorService threadPool = Executors . newFixedThreadPool(300 );
202
- // 一次只能允许执行的线程数量。
215
+ // 初始许可证数量
203
216
final Semaphore semaphore = new Semaphore (20 );
204
217
205
218
for (int i = 0 ; i < threadCount; i++ ) {
You can’t perform that action at this time.
0 commit comments