通过interrupt,设置了一个标识告诉线程可以终止了,线程中还提供了静态方法Thread.interrupted()对设置中断标识的线程复位。比如在上面的案例中,外面的线程调用thread.interrupt来设置中断标识,而在线程里面,又通过Thread.interrupted把线程的标识又进行了复位
public class InterruptDemo {
private static int i;
public static void
main(String[] args) throws
InterruptedException {
Thread thread=new
Thread(()->{
while(true){
if(Thread.currentThread().isInterrupted()){
System.out.println("before:"+Thread.currentThread().isInterrupted());
Thread.interrupted(); //对线程进行复
位,由true变成false
System.out.println("after:"+Thread.currentThread().isInterrupted());
}
}
},"interruptDemo");
thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt();
}
}