hooyantsing's Blog

9_Condition实现精准通知唤醒

字数统计: 302阅读时长: 1 min
2020/08/24

9 Condition实现精准通知唤醒

狂神说Java JUC并发编程最新版通俗易懂

Condition 可以精准的唤醒或等待某个线程。

相互通信的线程共用同一个 Condition

案例

线程按照顺序执行,A -> B -> C 。

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package demo1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class C {
public static void main(String[] args) {
Data3 data3 = new Data3();

new Thread(
() -> {
for (int i = 0; i < 10; i++) {
data3.printC();
}
}
).start();

new Thread(
() -> {
for (int i = 0; i < 10; i++) {
data3.printB();
}
}
).start();

new Thread(
() -> {
for (int i = 0; i < 10; i++) {
data3.printA();
}
}
).start();
}
}

class Data3 {

private Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private int number = 1;

public void printA() {
lock.lock();
try {
while (number != 1){
condition1.await();
}
System.out.println("A");
number = 2;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public void printB() {
lock.lock();
try {
while (number != 2){
condition2.await();
}
System.out.println("B");
number = 3;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public void printC() {
lock.lock();
try {
while (number != 3){
condition3.await();
}
System.out.println("C");
number = 1;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
CATALOG
  1. 1. 9 Condition实现精准通知唤醒
    1. 1.0.1. 案例