验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

如何中断一个正在执行的Runnable

阅读:628 来源:乙速云 作者:代码code

如何中断一个正在执行的Runnable

在Java中,要中断一个正在执行的Runnable,你可以使用Thread类的interrupt()方法。以下是一个简单的示例:

  1. 首先,创建一个实现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已停止");
    }
}
  1. 创建一个Thread对象,将MyRunnable实例作为参数传递,并启动线程:
public class Main {
    public static void main(String[] args) throws InterruptedException {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}
  1. 在需要中断线程的地方调用interrupt()方法:
// 假设在主线程中等待5秒后中断MyRunnable线程
Thread.sleep(5000);
thread.interrupt();

这样,当thread.interrupt()被调用时,MyRunnable线程中的run()方法会检测到中断状态,并在下次循环时退出。如果线程在等待、休眠或其他阻塞操作中被中断,InterruptedException将被抛出,你可以捕获这个异常并设置中断状态。

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>