forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbcSemaphore.java
More file actions
51 lines (47 loc) · 1.61 KB
/
AbcSemaphore.java
File metadata and controls
51 lines (47 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.concurrent.Semaphore;
/**
* 编写一个程序,开启三个线程,这三个线程的 ID 分别是 A、B 和 C,每个线程把自己的 ID 在屏幕上打印 10 遍,
* 要求输出结果必须按 ABC 的顺序显示,如 ABCABCABC... 依次递推
*
* 使用 Semaphore 实现
*/
public class AbcSemaphore {
public static void main(String[] args) {
Semaphore semaphoreA = new Semaphore(1);
Semaphore semaphoreB = new Semaphore(0);
Semaphore semaphoreC = new Semaphore(0);
new Thread(()->{
try {
while (true) {
semaphoreA.acquire();
System.out.print(Thread.currentThread().getName());
semaphoreB.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
new Thread(()->{
try {
while (true) {
semaphoreB.acquire();
System.out.print(Thread.currentThread().getName());
semaphoreC.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
new Thread(()->{
try {
while (true) {
semaphoreC.acquire();
System.out.println(Thread.currentThread().getName());
semaphoreA.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"C").start();
}
}