Thanks to visit codestin.com Credit goes to github.com
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent f7e0ffb commit 938724cCopy full SHA for 938724c
threads/SemaphoreDemo.java
@@ -0,0 +1,25 @@
1
+import java.util.concurrent.Semaphore;
2
+
3
+public class SemaphoreDemo {
4
+ public static void main(String[] args) {
5
+ // Semaphore 信号量,用于控制同时访问的线程数,通过维护一组许可证来实现
6
+ final Semaphore semaphore = new Semaphore(2);
7
8
+ for (int i = 0; i < 10; i++) {
9
+ int k = i;
10
+ new Thread(() -> {
11
+ try {
12
+ // semaphore 维护了 2 个许可证,这里取走一个(如果所有许可证都用光了,则阻塞)
13
+ semaphore.acquire();
14
+ System.out.printf("第 %d 位顾客购物中\n", k);
15
+ Thread.sleep(1000);
16
+ // 这里线程工作完毕后,给 semaphore 新增一个许可证,让下一个线程可以进来
17
+ semaphore.release();
18
+ System.out.printf("第 %d 位顾客购物完毕离开...\n", k);
19
+ } catch (Exception e) {
20
+ e.printStackTrace();
21
+ }
22
+ }).start();
23
24
25
+}
0 commit comments