我们根据interrupt方法的特点以及sleep等方法与interrupt互动的特性,我们可以写出两阶段终止的代码,如果我们在线程sleep的时候中断了线程,此时会出现异常,同时interrupt状态会被重置,那我们就可以在catch块内重新设置当前线程的interrupt状态,在下次循环中终止线程
@Slf4j
public class TPTInterrupt {
private Thread thread;
public void start() {
thread = new Thread(() -> {
while (true) {
var current = Thread.currentThread();
if (current.isInterrupted()) {
log.debug("料理后事");
break;
}
try {
TimeUnit.SECONDS.sleep(1);
log.debug("执行监控记录");
//todo 执行监控
} catch (InterruptedException e) {
current.interrupt();
e.printStackTrace();
}
}
}, "监控线程");
thread.start();
}
public void stop() {
thread.interrupt();
}
public static void main(String[] args) {
var tptInterrupt = new TPTInterrupt();
tptInterrupt.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
tptInterrupt.stop();
}
}
Q.E.D.