-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlternatePrint.java
More file actions
43 lines (30 loc) · 1.06 KB
/
AlternatePrint.java
File metadata and controls
43 lines (30 loc) · 1.06 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
package MutiThreading.src;
import java.util.concurrent.Semaphore;
public class AlternatePrint {
private static Semaphore[] semaphores;
private static final int ThreadNum = 3;
private static final int PrintNum = 10;
public static void main(String[] args) {
semaphores = new Semaphore[ThreadNum];
for (int i = 0; i < ThreadNum; i++) {
semaphores[i] = new Semaphore(0);
}
semaphores[0].release();
for (int i = 0; i < ThreadNum; i++) {
final int cur = i;
final int next = (i + 1) % ThreadNum;
new Thread(() -> {
for (int j = 0; j < PrintNum; j++) {
try {
semaphores[cur].acquire();
char c = (char) ('A' + cur);
System.out.println(c);
semaphores[next].release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}