0%

java | 设计模式 同步模式 交替输出 await & signal

使用 awaitsignal 来进行交替输出。

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

import lombok.extern.slf4j.Slf4j;

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

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

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

AwaitSignal awaitSignal = new AwaitSignal(5);
Condition a = awaitSignal.newCondition();
Condition b = awaitSignal.newCondition();
Condition c = awaitSignal.newCondition();

new Thread(() -> {
awaitSignal.print("a", a, b);
}).start();

new Thread(() -> {
awaitSignal.print("b", b, c);
}).start();

new Thread(() -> {
awaitSignal.print("c", c, a);
}).start();

// 主线程唤醒
Thread.sleep(1000);
awaitSignal.lock();
a.signal();
awaitSignal.unlock();
}

}

class AwaitSignal extends ReentrantLock {
private int loopNumber;

public AwaitSignal(int loopNumber) {
this.loopNumber = loopNumber;
}

// 参数 1 打印内容 参数2 进入哪一间休息室 参数 3 下一间休息室
public void print(String str, Condition current, Condition next) {
for (int i = 0; i < loopNumber; i++) {
lock();
try {
current.await();
System.out.println(str);
next.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
unlock();
}
}
}
}
请我喝杯咖啡吧~