使用 interrupt 来通知线程停止运行,而不是强制停止!
普通情况停止线程
public class RightWayStopThreadWithoutSleep implements Runnable {
@Override
public void run() {
int num = 0;
while (!Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE / 2) {
if (num % 10000 == 0) {
System.out.println(num + "是1W的倍数");
}
num++;
}
System.out.println("任务运行结束!");
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new RightWayStopThreadWithoutSleep());
thread.start();
// 等待1s
Thread.sleep(1000);
// 通知停止线程
thread.interrupt();
}
}
使用 thread.interrupt() 通知线程停止
但是 线程需要配合:
在 while 中使用 Thread.currentThread().isInterrupted() 检测线程当前的状态
运行结果:
……
……
221730000是1W的倍数
221740000是1W的倍数
221750000是1W的倍数
221760000是1W的倍数
221770000是1W的倍数
221780000是1W的倍数
221790000是1W的倍数
221800000是1W的倍数
任务运行结束!
Process finished with exit code 0
在可能被阻塞情况下停止线程
public class RightWayStopThreadWithSleep {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = () -> {
int num = 0;
while (num <= 300 && !Thread.currentThread().isInterrupted()) {
if (num % 100 == 0) {
System.out.println(num + "是100的倍数");