gpt4 book ai didi

java - 如果 sleep 中断线程被唤醒,是否应该中断自身?

转载 作者:行者123 更新时间:2023-12-04 00:50:15 25 4
gpt4 key购买 nike

线程一直工作到被打断但时不时会 hibernate :

public void run() {
while (!Thread.interrupted()) {
//A TASK HERE
try {
Thread.sleep((long) (500 + Math.random() * 100));
} catch (InterruptedException e) {
interrupt(); //it was interrupted while it was sleeping
}
}
}

目的是通过中断来杀死线程。我可以像以前那样重新中断自身,还是应该在异常子句中设置一个标志 stop = true

最佳答案

在循环外捕获中断:

public void run() {
try {
while (true) {
//A TASK HERE
Thread.sleep((long) (500 + Math.random() * 100));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

无论您在哪里捕捉到 InterruptedException,如果您真的没有处理它,最好重新中断当前线程,并且您不能简单地抛出InterruptedException(例如,因为它位于未声明抛出 InterruptedExceptionExceptionThrowable 的方法中).

这允许 run() 方法的调用者知道执行被中断,因此他们也可以停止他们正在做的事情。

您可能决定不重新中断线程的主要情况是,如果您正在编写某种线程框架(如 Executors),您可以在其中重用先前中断的线程来执行下一个任务。

关于java - 如果 sleep 中断线程被唤醒,是否应该中断自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67270296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com