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
中的并发线程破坏。这是我的代码流程:
MyRunnable
executor
等待10秒钟完成任务。executor
类应该终止该线程。除了最后一个场景中的任务终止外,一切正常。我该怎么办?
答案 0 :(得分:16)
shutDown()
方法只是阻止安排其他任务。相反,您可以致电shutDownNow()
并检查Runnable
中的线程中断。
// in your Runnable...
if (Thread.interrupted()) {
// Executor has probably asked us to stop
}
基于您的代码的示例可能是:
final ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(new Runnable() {
public void run() {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
System.out.println("Interrupted, so exiting.");
}
}
});
if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
System.out.println("task completed");
} else {
System.out.println("Forcing shutdown...");
executor.shutdownNow();
}
答案 1 :(得分:2)
从外部终止正在运行的线程通常是一个坏主意,因为你不知道线程当前所处的状态。它可能需要做一些清理,而且它不能当你强行关闭它时这样做。 That's why all methods of Thread which do that are marked as deprecated
使用许多可用于进程间通信的技术之一来告知线程本身运行的过程,它必须中止其工作并正常退出,这样做要好得多。一种方法是向runnable添加abort()
方法,该方法引发一个声明为volatile
的标志。 Runnable的内部循环检查该标志并在引发该标志时以受控方式退出。