是否可以中断ExecutorService的特定线程? [英] Is it possible to interrupt a specific thread of an ExecutorService?

查看:671
本文介绍了是否可以中断ExecutorService的特定线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 ExecutorService 我向其提供Runnable任务,我可以选择一个并中断吗?
b
我知道我可以取消返回未来(也提到这里:如何中断执行者 - 线程),但是如何提出 InterruptedException 。取消似乎没有这样做(事件虽然它应该通过查看源,可能OSX实现不同)。至少这个片段不打印'它!'也许我误解了一些东西而且不是自定义runnable获得异常?

If I have an ExecutorService to which I feed Runnable tasks, can I select one and interrupt it?
I know I can cancel the Future returned (also mentioned Here: how-to-interrupt-executors-thread), but how can I raise an InterruptedException. Cancel doesn't seem to do it (event though it should by looking at the sources, maybe the OSX implementation differs). At least this snippet doesn't print 'it!' Maybe I'm misunderstaning something and it's not the custom runnable that gets the exception?

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

The right thing to do here is to cancel the Future. The issue is that this will not necessarily cause an InterruptedException.

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

If the job has yet to run then it will be removed from the runnable queue -- I think this is your problem here. If the job has already finished then it won't do anything (of course). If it is still running then it will interrupt the thread.

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

Interrupting a thread will only cause sleep(), wait(), and some other methods to throw InterruptedException. You will also need test to see if the thread has been interrupted with:

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

此外,如果你抓住<$,重新设置中断标志是一个很好的模式c $ c> 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)。可能是您在之前取消未来它有机会执行。

In your code, I would try putting a sleep before you call lo.cancel(true). It may be that you are canceling the future before it gets a chance to execute.

这篇关于是否可以中断ExecutorService的特定线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆