Java 已经不推荐使用 stop() 关闭线程
使用 interrupt() 方法关闭线程,不会像stop() 那样直接关闭线程,会等待正在执行的线程结束后关闭线程,以下是调用了interrupt() 方法仍然不能关闭线程的代码。
public class MyTask implements Runnable {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
System.out.println(thread.getId());
try {
Thread.sleep(10000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread" + thread.getId());
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
// 任务逻辑
// ...
System.out.println("输出任务逻辑");
// 休眠一段时间
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
通过运行代码,我们知道上面的线程没有被关闭。
java.lang.InterruptedException: sleep interrupted
这个异常表示线程在休眠或阻塞时被中断。当一个线程在休眠(Thread.sleep()
)或者在等待(Object.wait()
或者Thread.join()
等方法)的时候,如果其他线程调用了该线程的interrupt()
方法,那么这个线程的sleep()
或者wait()
等调用将被唤醒,并且会抛出InterruptedException
。
在 catch 的时候重新调用中断方法。
public class MyTask implements Runnable {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
System.out.println(thread.getId());
try {
Thread.sleep(10000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread" + thread.getId());
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
// 任务逻辑
// ...
System.out.println("输出任务逻辑");
// 休眠一段时间
Thread.sleep(1000);
} catch (InterruptedException e) {
// 如果线程被中断,处理中断异常
// 这里可以设置running为false来停止循环
// 可以设置中断状态为true来处理中断
Thread.currentThread().interrupt();
}
}
}
}