【发布时间】:2013-03-31 18:59:42
【问题描述】:
final ExecutorService executor = Executors.newFixedThreadPool(1);
final Future<?> future = executor.submit(myRunnable);
executor.shutdown();
if(executor.awaitTermination(10, TimeUnit.SECONDS)) {
System.out.println("task completed");
}else{
System.out.println("Executor is shutdown now");
}
//MyRunnable method is defined as task which I want to execute in a different thread.
这里是执行器类的run方法:
public void run() {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
这里它正在等待20 秒,但是当我运行代码时它会引发异常:
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
我无法关闭在Java Executor class 中破坏的并发线程。这是我的代码流程:
- 使用 Java 执行器类创建了一个新线程来运行一些任务,即用
MyRunnable编写 -
executor等待 10 秒完成任务。 - 如果任务已完成,则可运行线程也会终止。
- 如果任务未在 10 秒内完成,则
executor类应终止线程。
除了最后一个场景中的任务终止之外,一切正常。我该怎么做?
【问题讨论】:
标签: java multithreading executorservice