Java Interrupt 线程中断

本文详细介绍了Java中线程中断的原理,包括如何设置中断标记、检查中断状态以及如何响应中断。讨论了中断在优雅终止线程和处理取消请求中的应用,并提供了示例代码以展示其用法。
摘要由CSDN通过智能技术生成

线程中断是一种向线程发出的信号机制,通知线程应该停止正在做的事情并正常终止。它不会强制终止线程,而是为线程提供了一种协作方式来响应中断请求。中断通常用于停止长时间运行或阻塞的线程,而无需终止线程。

Java 线程中断使用案例

设置线程中断标记

Thread newThread = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        // Long running task
    }
});

newThread.start();
// Later in the code
newThread.interrupt(); // Set the interrupt flag

检查中断标记

while (!Thread.currentThread().isInterrupted()) {
    // Long running task
}

响应线程中断
当线程的中断标志被设置时,由线程决定如何响应。常见的响应包括清理资源、关闭套接字或文件以及退出线程的运行方法。

// 如果线程被中断,退出循环
while (!Thread.currentThread().isInterrupted()) {
    // Long running task
}

中断异常
线程阻塞或者睡眠的时候,收到中断信号,会抛出中断异常。我们可以捕获这个异常来优雅地处理中断。

try {
    Thread.sleep(10000);
} catch (InterruptedException e) {
    // Handle the interruption or re-interrupt the thread
}

清除中断标记

boolean wasInterrupted = Thread.interrupted();

需要注意的是,线程中断是一种协作机制。线程有责任检查其中断状态并做出适当的响应。线程中断通常用于优雅地终止线程或处理取消请求。

下面有一个例子,使用线程中断来停止一个线程。

Thread workerThread = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
       // Long running task
    }
    System.out.println("Thread is interrupted and exiting.");
});

workerThread.start();

// Later in the code, we can stop the thread by interrupting it
workerThread.interrupt();

这个例子中,我们使用 interrupt(),给线程设置中断标记,使得线程能够优雅地退出循环和终止。

😄

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值