forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbcLockCondition.java
More file actions
65 lines (58 loc) · 1.93 KB
/
AbcLockCondition.java
File metadata and controls
65 lines (58 loc) · 1.93 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
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 编写一个程序,开启三个线程,这三个线程的 ID 分别是 A、B 和 C,每个线程把自己的 ID 在屏幕上打印 10 遍,
* 要求输出结果必须按 ABC 的顺序显示,如 ABCABCABC... 依次递推
*
* 使用 Lock 搭配 Condition 实现
*/
public class AbcLockCondition {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Condition a = lock.newCondition();
Condition b = lock.newCondition();
Condition c = lock.newCondition();
new Thread(()-> {
while (true) {
lock.lock();
System.out.print(Thread.currentThread().getName());
b.signal();
try {
a.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}, "A").start();
new Thread(()-> {
while (true) {
lock.lock();
System.out.print(Thread.currentThread().getName());
c.signal();
try {
b.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}, "B").start();
new Thread(()-> {
while (true) {
lock.lock();
System.out.println(Thread.currentThread().getName());
a.signal();
try {
c.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}, "C").start();
}
}