在固定时间后中断线程,它是否必须抛出InterruptedException?
我想在一段固定的时间后中断一个线程。 其他人问了同样的问题,最高投票的答案( https://stackoverflow.com/a/2275596/1310503 )给出了下面的解决方案,我稍微缩短了。
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 { 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 /演示目的。 只需在那里进行长时间运行的任务而不是睡觉()。
但是如果你替换Thread.sleep(4000);
with for (int i = 0; i < 5E8; i++) {}
然后它不编译,因为空循环不会抛出InterruptedException。 并且为了使线程可以中断,它需要抛出InterruptedException。
有没有办法让上面的代码与一般的长期运行任务而不是sleep()
?
如果您希望操作可以中断(即应该可以在它完成之前中断它),您需要使用其他可中断操作(Thread.sleep,InputStream.read, 读取更多信息 )或手动检查线程中断状态。你的循环条件使用Thread.isInterrupted。
你误会了。
“……对于可中断的线程,它需要抛出一个InterruptedException”根本就不是这样。 那个catch块只是因为Thread.sleep()
方法抛出InterruptedException
。 如果您没有使用sleep(或任何其他可以抛出InterruptedException
代码),那么您不需要catch块。
您可以检查线程的中断状态,例如:
public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); executor.invokeAll(Arrays.asList(new Task()), 2, TimeUnit.SECONDS); executor.shutdown(); } static class Task implements Callable { public String call() throws Exception { System.out.println("Started.."); for (int i = 0; i < Integer.MAX_VALUE; i++) { if (Thread.currentThread().isInterrupted()) { System.out.println("Interrupted!"); return null; } } System.out.println("Finished!"); return null; } }
如果替换sleep
,则所有代码都不会抛出InterruptedException
。 您应该删除InterruptedException
的try-catch:
public String call() { System.out.println("Started.."); for (int i = 0; i < 5E8; i++) {} System.out.println("Finished!"); return null; }
- Spring Batch:org.springframework.batch.item.ReaderNotOpenException:Reader必须先打开才能读取
- 尝试在google app engine for java中实现异步http时遇到奇怪的exception
- Java EE应用程序范围的变量在集群环境(Websphere)中?
- 如何在属性文件中指定值,以便可以使用ResourceBundle#getStringArray检索它们?
- 警告org.apache.maven.plugins的’build.plugins.plugin.version’:缺少maven-deploy-plugin
- 什么时候Java线程活着?
- Java增量/减量运算符 – 它们的行为方式,function是什么?
- 在单个web.xml中添加多个servlet
- 如何在Java中获得真正的字符串高度?