如何在java执行器类中停止所有可运行的线程?
问题描述:
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.
这是运行
执行者类的方法:
Here is run
method of executor class:
public void run() {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
这里等待 20
秒但是当我运行代码时会抛出异常:
Here it is waiting for 20
second but when i run the code it throws an exception:
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
我无法关闭 Java Executor类
中的并发线程破坏。这是我的代码流程:
I am not able to close the concurrent thread ruining in Java Executor class
. Here is my Code flow:
- 创建一个带有Java执行器类的新线程来运行一些任务,即用
MyRunnable编写
-
executor
等待10秒钟完成任务。 - 如果任务已经完成,那么runnable线程也会被终止。
- 如果任务没有在10秒内完成,那么 executor class应该终止线程。
- Created a new Thread with Java executor class to run some task i.e written in
MyRunnable
-
executor
wait for 10 second to complete the tasks. - If the task has completed then runnable thread also got terminated.
- If the task is not completed within 10 second then
executor
class should terminate the thread.
除了上一个场景中的任务终止外,一切正常。我该怎么办?
Everything works fine except the termination of tasks in the last scenario. How should I do it?
答
shutDown()
方法只是阻止安排其他任务。相反,您可以调用 shutDownNow()
并检查 Runnable
中的线程中断。
// in your Runnable...
if (Thread.interrupted()) {
// Executor has probably asked us to stop
}
根据您的代码,一个例子可能是:
An example, based on your code, might be:
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();
}