interrupt()打断每个线程(设置标志位)
isInterrupted()查询某个线程是否被打断过(查询标志位)
static interrupted()查询当前线程是否被打断过,并重置打断标志
当线程sleep或wait、join时,如果这时设置标志位会产生InterruptedException异常,catch后可以进行处理,标志位也会复位。
锁操作不会被Interrupte()干扰
lockInterruptibly()可以干扰,使其抛出异常,catch异常后可以进行自定义操作。
面试题:怎么优雅的结束一个线程
不建议使用stop()方法。容易产生数据不一致的问题,stop方法太粗暴了。suspend和resume方法也是同样的。
1、设置标志位结束线程
for (;;){
if (Thread.currentThread().isInterrupted()) {
break;//设置过标志位就结束线程
}
}
2、使用volatile 变量(不依赖中间状态时使用)
private static volatile boolean running =true;
public static void main(String[] args) {
Thread t = new Thread(()-> {
while (running){
System.out.println("a");
}
});
t.start();
running=false;
}