当面试官问你如何关闭一个线程?
如果你回答用stop方法,你会发现面试官会看憨憨一样看你,stop是一种强制性
关闭,是直接调用jvm底层来实现强行关闭
那么如何正确关闭一个线程呢?
1.使用volatile共享变量,来关闭一个线程
2.interrupt
代码示例:
package com.hzh.interrupt;
public class TestInterrupt {
private static int i = 0;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (!Thread.currentThread().isInterrupted()){
i++;
}
});
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
如果有面试官问什么时候会抛出InterruptedException异常
在线程阻塞的时候调用interrupt方法,此时为抛出此异常
代码示例:
package com.hzh.interrupt;
public class TestInterrupt {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (!Thread.currentThread().isInterrupted()){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}