public class StopGenteelly {
public static void main(String[] args) throws InterruptedException {
TwoPhaseTermination tpt = new TwoPhaseTermination();
tpt.start();
Thread.sleep(100);
tpt.stop();
}
}
class TwoPhaseTermination{
private Thread thread;
public void start(){
thread = new Thread(()->{
while (true){
if (thread.isInterrupted()){
System.out.println("线程被中断,结束线程");
break;
}
try {
System.out.println("做一些工作。。。");
Thread.sleep(1000); //在这里中断,会抛出InterruptedException
} catch (InterruptedException e) {//中断标记会被重置
e.printStackTrace();
thread.interrupt();
}
}
});
thread.start();
}
public void stop(){
thread.interrupt();
System.out.println("中断线程");
}
}
如果我们需要中断的线程的run()
方法中有sleep
,wait
,join
操作,那么在执行这些操作之后,线程进入阻塞状态,中断阻塞状态的线程会抛出InterruptedException
异常,并且在抛出异常时会将中断标志重置为false
,所以在捕获到这个异常时,重新将中断标志置为true
是十分必要的,否则线程将不会被中断。