JUC--设计模式_两阶段终止模式 Two Phase Termination

JUC–两阶段终止模式 Two Phase Termination

背景

  • JUC–两阶段终止模式 Two Phase Termination

  • 博主以黑马JUC进行学习

两阶段终止模式 Two Phase Termination

  • 在一个线程T1中如何优雅的终止线程T2?这里的优雅指的是给T2一个料理后事的机会。
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
public class Test3{
public static void main(String[] args){
TwoPhaseTermination tpt = new TwoPhaseTermination();
tpt.start();
Thread.sleep(3500);
tpt.stop();
}
}

class TwoPhaseTermination{
private Thread monitor;

//启动监控线程
public void start(){
monitor = new Thread(() -> {
while(true){
Thread current = Thread.currentThread();
//是否被打断
if(current.isInterrupted()){
log.debug("料理后事");
break;
}
try{
Thread.sleep(1000);
log.debug("执行监控记录");
}catch (InterruptedException e){
e.printStackTrace();
//重新设置打断标记
current.interrupt();
}
}
});

monitor.start();
}

//停止监控线程
public void stop(){
monitorThread.interrupt();
}
}