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
|
public class ThreadPrint2Test {
public static void main(String[] args) {
new ThreadPrint2Test().testPrint();
}
public void testPrint() {
Lock lock = new ReentrantLock();
Condition conditionA = lock.newCondition();
Condition conditionB = lock.newCondition();
Condition conditionC = lock.newCondition();
new Thread(new PrintThread("A", lock, conditionA, conditionB), "thread-a").start();
new Thread(new PrintThread("B", lock, conditionB, conditionC), "thread-b").start();
new Thread(new PrintThread("C", lock, conditionC, conditionA), "thread-c").start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
new Thread(() -> {
lock.lock();
conditionA.signal();
lock.unlock();
}, "init").start();
}
class PrintThread implements Runnable {
private Lock lock;
private Condition ca;
private Condition cb;
private String value;
public PrintThread(String value, Lock lock, Condition ca, Condition cb) {
this.value = value;
this.lock = lock;
this.ca = ca;
this.cb = cb;
}
public void run() {
while (true) {
try {
lock.lock();
ca.await();
System.out.println(value);
Thread.sleep(500);
cb.signal();
lock.unlock();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
|