use*_*503 5 java concurrency timeout
我想在一段固定的时间后中断一个线程.其他人问了同样的问题,最高投票的答案(/sf/answers/159291751/)给出了下面的解决方案,我稍微缩短了.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
他们补充道:
sleep()不是必需的.它仅用于SSCCE /演示目的.只是在那里做长期运行的任务而不是睡觉().
但是如果你Thread.sleep(4000);用for (int i = 0; i < 5E8; i++) {}它替换它就不会编译,因为空循环不会抛出InterruptedException.并且为了使线程可以中断,它需要抛出InterruptedException.
是否有任何方法可以使上述代码与一般的长期运行任务一起工作而不是sleep()?
如果你希望你的动作是可中断的(即应该可以在它完成之前中断它)你需要使用其他可中断的动作(Thread.sleep、InputStream.read、read for more info)或手动检查线程中断状态您使用 Thread.isInterrupted 的循环条件。
| 归档时间: |
|
| 查看次数: |
2384 次 |
| 最近记录: |