在固定时间后中断线程,是否必须抛出InterruptedException? [英] interrupting a thread after fixed time, does it have to throw InterruptedException?

查看:183
本文介绍了在固定时间后中断线程,是否必须抛出InterruptedException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在固定时间后中断一个线程。有人提出了同样的问题,以及最常投票的答案( http://stackoverflow.com/a/2275596/1310503)给出了下面的解决方案,我稍微缩短了。

I want to interrupt a thread after a fixed amount of time. Someone else asked the same question, and the top-voted answer (http://stackoverflow.com/a/2275596/1310503) gave the solution below, which I have slightly shortened.

import java.util.Arrays;
import java.util.concurrent.*;

public class Test {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.invokeAll(Arrays.asList(new Task()), 2, TimeUnit.SECONDS);
        executor.shutdown();
    }
}

class Task implements Callable<String> {
    public String call() throws Exception {
        try {
            System.out.println("Started..");
            Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
            System.out.println("Finished!");
        } catch (InterruptedException e) {
            System.out.println("Terminated!");
        }
        return null;
    }
}

他们添加:


不需要sleep()。它仅用于SSCCE /演示目的。

the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep().

但是如果你替换 Thread。 sleep(4000); with for(int i = 0; i <5E8; i ++){} 空循环不会抛出一个InterruptedException。对于线程是可中断的,它需要抛出一个InterruptedException。

But if you replace Thread.sleep(4000); with for (int i = 0; i < 5E8; i++) {} then it doesn't compile, because the empty loop doesn't throw an InterruptedException. And for the thread to be interruptible, it needs to throw an InterruptedException.

有任何方法使上述代码与一个长期运行的任务, code> sleep()?

Is there any way of making the above code work with a general long-running task instead of sleep()?

推荐答案

如果您希望操作是可中断的(即应该可以在完成之前中断它),您需要使用其他可中断的操作(Thread.sleep,InputStream.read,阅读更多信息)或手动检查线程中断状态在您的周期条件使用Thread.isInterrupted。

If you want you action to be interruptable (i.e. it should be possible to interrupt it before it's completed) you need to either use other interruptable action (Thread.sleep, InputStream.read, read for more info) or manually check thread interruption status in your cycle condition using Thread.isInterrupted.

这篇关于在固定时间后中断线程,是否必须抛出InterruptedException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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