优雅终止线程
终止线程
一个实际例子
public class MonitorSystemProxy {
// 保证只启动一次
private boolean started = false;
private Thread rptThread;
// 开启采集功能
public synchronized void start() {
if (started) {
return;
}
started = true;
rptThread = new Thread(() -> {
// 线程终止状态位,检测到 interrupt 指令就退出
while (!Thread.currentThread().isInterrupted()) {
// 采集上报的逻辑实现
// report();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// 当 catch 到 InterruptedException 状态标识位被清空
// 重新设置状态位
Thread.currentThread().interrupt();
}
}
started = false;
});
rptThread.start();
}
// 终止采集功能
public synchronized void stop() {
// 发送终止命令,interrupt()
rptThread.interrupt();
}
}线程池的终止和退出
最后更新于