0%

java | 设计模式 同步模式 两阶段终止

代码很简单就是

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

import lombok.extern.slf4j.Slf4j;

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

public static void main(String[] args) throws InterruptedException {
TwoPhaseTermination tpt = new TwoPhaseTermination();
tpt.start();

Thread.sleep(3000);
tpt.stop();
}
}

@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination {
private Thread monitor;
volatile private boolean stop = false;

public void start() {
monitor = new Thread(() -> {
while (true) {
Thread current = Thread.currentThread();
if (stop) {
log.debug("料理后事");
break;
}
try {
Thread.sleep(1000);
log.debug("执行监控");// 如果睡眠过程中被打断,则会进入到下面的异常
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
monitor.start();
}

public void stop() {
stop = true;
}
}
请我喝杯咖啡吧~