如何中断一个正在执行的Runnable
在Java中,要中断一个正在执行的Runnable,你可以使用Thread类的interrupt()方法。以下是一个简单的示例:
- 首先,创建一个实现
Runnable接口的类,并在run()方法中检查线程的中断状态:
class MyRunnable implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// 在这里执行你的任务
System.out.println("Runnable正在执行...");
try {
Thread.sleep(1000); // 假设这是一个耗时操作
} catch (InterruptedException e) {
// 当线程被中断时,捕获InterruptedException并设置中断状态
Thread.currentThread().interrupt();
System.out.println("Runnable被中断");
}
}
System.out.println("Runnable已停止");
}
}
- 创建一个
Thread对象,将MyRunnable实例作为参数传递,并启动线程:
public class Main {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
- 在需要中断线程的地方调用
interrupt()方法:
// 假设在主线程中等待5秒后中断MyRunnable线程
Thread.sleep(5000);
thread.interrupt();
这样,当thread.interrupt()被调用时,MyRunnable线程中的run()方法会检测到中断状态,并在下次循环时退出。如果线程在等待、休眠或其他阻塞操作中被中断,InterruptedException将被抛出,你可以捕获这个异常并设置中断状态。