Java 线程关闭:使用 interrupt() 方法
在 Java 中,要关闭线程,可以使用 Thread 类的 interrupt() 方法。这个方法会设置线程的中断状态,告诉线程应该停止执行。
可以在 run() 方法中检查线程的中断状态,如果被设置了,就退出线程。例如:
public class MyThread extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
// 线程执行的任务
}
}
}
// 关闭线程的代码
MyThread thread = new MyThread();
thread.start();
// 等待一段时间
Thread.sleep(5000);
thread.interrupt();
在上面的例子中,MyThread 类继承了 Thread 类,并重写了 run() 方法。在 run() 方法中,使用了 isInterrupted() 方法来判断线程是否被中断,如果被中断了,就退出循环。
在关闭线程的代码中,先创建 MyThread 对象并启动线程,然后等待一段时间,最后调用 interrupt() 方法来关闭线程。这个方法会把线程的中断状态设置为 true,这样线程就会退出循环,停止执行。
原文地址: https://www.cveoy.top/t/topic/n6Vk 著作权归作者所有。请勿转载和采集!