-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintlnABC.java
More file actions
79 lines (70 loc) · 2.27 KB
/
PrintlnABC.java
File metadata and controls
79 lines (70 loc) · 2.27 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package ThreadTest;
public class PrintlnABC {
public static class Worker {
Object lock = new Object();
int flag = 1;
public void PrintA() {
synchronized (lock) {
while (flag != 1) {
try {
lock.wait(); //释放锁,当前拥有该锁的线程进入等待状态,需要被唤醒,所以在执行打印之前要调用notify方法
} catch (InterruptedException e) {
// TODO: handle exception
}
}
flag = 2;
lock.notifyAll(); // 唤醒所有在等待该锁的线程
System.out.print(Thread.currentThread().getName());
}
}
public void PrintB() {
synchronized (lock) {
while (flag != 2) {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO: handle exception
}
}
flag = 3;
lock.notifyAll();
System.out.print(Thread.currentThread().getName());
}
}
public void PrintC() {
synchronized (lock) {
while (flag != 3) {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO: handle exception
}
}
flag = 1;
lock.notifyAll();
System.out.print(Thread.currentThread().getName());
}
}
}
public static void main(String[] args) {
Worker worker = new Worker();
Thread threadA = new Thread(() -> {
for (int i = 0; i < 10; i++) {
worker.PrintA();
}
}, "A");
Thread threadB = new Thread(() -> {
for (int i = 0; i < 10; i++) {
worker.PrintB();
}
}, "B");
Thread threadC = new Thread(() -> {
for (int i = 0; i < 10; i++) {
worker.PrintC();
}
}, "C");
threadA.start();
threadB.start();
threadC.start();
}
}