-
两阶段终止(Two Phase Termination)
在一个线程T1中如何“优雅”地终止线程T2?优雅是说给T2一个料理后事的机会,比如释放锁。
其实很简单,就是定时地判断是否被打断,如果被打断了就料理后事自动退出。如果是sleep,wait,join这些会抛出异常,可以在这里设置打断的标记,之后再判断。 -
代码
面向对象的写法
public class TPTInterruptedThread {
private Thread thread;
public void start() {
thread = new Thread(
()->{
while(true) {
if(thread.isInterrupted()){
System.out.println("料理后事...");
break;
}
System.out.println("doing things...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// e.printStackTrace();
thread.interrupt();
}
}
}
);
thread.start();
}
public void stop() {
thread.interrupt();
}
}
- 测试
TPTInterruptedThread thread = new TPTInterruptedThread();
thread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// e.printStackTrace();
}
thread.stop();
输出
doing things...
doing things...
doing things...
料理后事...
网友评论