Skip to content

Commit 92c4348

Browse files
committed
多线程交替打印
1 parent f5e0dcd commit 92c4348

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.concurrent.Semaphore;
2+
3+
public class AlternatePrint
4+
{
5+
private static Semaphore[] semaphores;
6+
private static final int ThreadNum = 3;
7+
private static final int PrintNum = 10;
8+
9+
public static void main(String[] args)
10+
{
11+
semaphores = new Semaphore[ThreadNum];
12+
for (int i = 0; i < ThreadNum; i++) {
13+
semaphores[i] = new Semaphore(0);
14+
}
15+
semaphores[0].release();
16+
17+
for (int i = 0; i < ThreadNum; i++) {
18+
final int cur = i;
19+
final int next = (i + 1) % ThreadNum;
20+
new Thread(() -> {
21+
for (int j = 0; j < PrintNum; j++) {
22+
try {
23+
semaphores[cur].acquire();
24+
char c = (char)('A' + cur);
25+
System.out.println(c);
26+
semaphores[next].release();
27+
} catch (InterruptedException e) {
28+
e.printStackTrace();
29+
}
30+
}
31+
}).start();
32+
}
33+
}
34+
}

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
| Graph
1111
| ---- KruskalMST // Kruskal 最小生成树
1212
| ---- PrimMST // Prim 最小生成树
13+
| MultiThreading
14+
| ---- AlternatePrint // 多线程交替打印
1315
| Other
1416
| ---- Hanoi // 汉诺塔
1517
| ---- Huffman // 哈夫曼编码

0 commit comments

Comments
 (0)