我希望在固定的时间后中断一个线程。有人问了同样的问题,而且得到了得票最高的答案(https://dev59.com/IHE95IYBdhLWcg3wheRR#2275596),我稍微简化了一下这个解决方案。
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/演示目的。只需在其中执行您的长时间运行任务而非 sleep()。但是,如果您将 Thread.sleep(4000); 替换为 for (int i = 0; i < 5E8; i++) {},则无法编译,因为空循环不会抛出 InterruptedException。而线程要可中断,就需要抛出 InterruptedException。有没有办法让上述代码可以使用一般的长时间运行任务来替代 sleep() 呢?