两阶段终止模式
优雅地终止线程
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
| import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "Test3") public class Test3 { public static void main(String[] args) throws InterruptedException { TwoStageTermination t = new TwoStageTermination(); t.start(); Thread.sleep(5000); t.stop(); } }
@Slf4j(topic = "TwoStageTermination") class TwoStageTermination{ 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(){ monitor.interrupt(); } }
|
interrupt相关
- 打断
关于interrupt的api
isInterrupted() |
判断是否被打断 |
不会清除打断标记 |
interrupted() |
static方法,判断是否被打断 |
会清除打断标记(设为false) |
interrupt() |
打断线程 |
如果打断阻塞线程,会抛出InterruptedException异常,并清除打断标记(设为false);如果打算正常线程,则会设置打断标记(设为true);park线程也会被打断,也会设置打断标记 |
- 打断阻塞线程(sleep、join、wait)
打断sleep线程,会抛出异常, 清空打断状态,即打断标记为false
- 打断正常线程
不会对线程产生影响,设置打断标记,设为true