0%

java | 设计模式 同步模式 交替输出 wait & notify

这里的原理类似链表。

记录下一个的执行 flag,只有 flag 相同的时候,才会执行。

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
package com.redisc;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.Run")
public class Run {

public static void main(String[] args) throws Exception {

WaitNotify wn = new WaitNotify(1, 5);

new Thread(() -> {
wn.print("a", 1, 2);
}).start();
new Thread(() -> {
wn.print("b", 2, 3);
}).start();
new Thread(() -> {
wn.print("c", 3, 1);
}).start();
}

}

class WaitNotify {

private int flag;
private int loopNumber;

public WaitNotify(int flag, int loopNumber) {
this.flag = flag;
this.loopNumber = loopNumber;
}

public void print(String str, int waitFlag, int nextFlag) {
for (int i = 0; i < loopNumber; i++) {
synchronized (this) {
while (flag != waitFlag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(str);
flag = nextFlag;
this.notifyAll();
}
}
}
}

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
a
b
c
a
b
c
a
b
c
a
b
c
a
b
c
请我喝杯咖啡吧~