File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed
Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 1010| Graph
1111| ---- KruskalMST // Kruskal 最小生成树
1212| ---- PrimMST // Prim 最小生成树
13+ | MultiThreading
14+ | ---- AlternatePrint // 多线程交替打印
1315| Other
1416| ---- Hanoi // 汉诺塔
1517| ---- Huffman // 哈夫曼编码
You can’t perform that action at this time.
0 commit comments