-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAlternatePrintABCS.java
More file actions
69 lines (43 loc) · 1.28 KB
/
AlternatePrintABCS.java
File metadata and controls
69 lines (43 loc) · 1.28 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
package multithreading;
/**
* @Author: Wenhang Chen
* @Description:交替打印ABC,synchronized实现
* @Date: Created in 16:31 4/4/2020
* @Modified by:
*/
public class AlternatePrintABCS {
private final static Object lock = new Object();
private static int state = 0;
static class Task implements Runnable {
private int num;
private String name;
public Task(String name, int num) {
this.name = name;
this.num = num;
}
@Override
public void run() {
int i = 0;
while (i < 5) {
synchronized (lock) {
while (state % 3 != num) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.name);
state++;
i++;
lock.notifyAll();
}
}
}
}
public static void main(String[] args) {
new Thread(new Task("A", 0)).start();
new Thread(new Task("B", 1)).start();
new Thread(new Task("C", 2)).start();
}
}