gpt4 book ai didi

java - 是否可以中断 ExecutorService 的特定线程?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:56:19 24 4
gpt4 key购买 nike

如果我有一个 ExecutorService 并向其提供 Runnable 任务,我可以选择一个并中断它吗?
我知道我可以取消返回的 Future(也提到了 Here: how-to-interrupt-executors-thread ),但是我怎样才能引发 InterruptedException。 Cancel 似乎没有这样做(尽管它应该通过查看源代码来实现,也许 OSX 实现不同)。至少这个片段不会打印“它!”也许我误解了什么,不是自定义可运行程序导致异常?

public class ITTest {
static class Sth {
public void useless() throws InterruptedException {
Thread.sleep(3000);
}
}

static class Runner implements Runnable {
Sth f;
public Runner(Sth f) {
super();
this.f = f;
}
@Override
public void run() {
try {
f.useless();
} catch (InterruptedException e) {
System.out.println("it!");
}
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newCachedThreadPool();
Sth f = new Sth();
Future<?> lo = es.submit(new Runner(f));
lo.cancel(true);
es.shutdown();
}

最佳答案

这里正确的做法是取消Future。问题是这不一定会导致 InterruptedException

如果作业尚未运行,那么它将从可运行队列中删除——我认为这是您的问题。如果工作已经完成,那么它不会做任何事情(当然)。如果它仍在运行,那么它将中断线程

中断线程只会导致sleep()wait()和其他一些方法抛出InterruptedException。您还需要测试线程是否已被中断:

if (Thread.currentThread().isInterrupted()) {

此外,如果捕获到 InterruptedException,重新设置中断标志是一个很好的模式:

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// this is a good pattern otherwise the interrupt bit is cleared by the catch
Thread.currentThread().interrupt();
...
}

在您的代码中,我会尝试在您调用lo.cancel(true) 之前 hibernate 。可能是您在 有机会执行之前取消了 future 。

关于java - 是否可以中断 ExecutorService 的特定线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12060279/

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