Ami*_*Pal 13 java multithreading executorservice
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 Code Online (Sandbox Code Playgroud)
这是run
执行者类的方法:
public void run() {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
Run Code Online (Sandbox Code Playgroud)
在这里它等待20
第二,但是当我运行代码时它抛出一个异常:
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
Run Code Online (Sandbox Code Playgroud)
我无法关闭并发线程破坏Java Executor class
.这是我的代码流程:
MyRunnable
executor
等待10秒钟完成任务.executor
类应终止该线程.除了最后一个场景中的任务终止外,一切正常.我该怎么办?
Dun*_*nes 16
该shutDown()
方法仅阻止安排其他任务.相反,你可以调用shutDownNow()
并检查你的线程中断Runnable
.
// in your Runnable...
if (Thread.interrupted()) {
// Executor has probably asked us to stop
}
Run Code Online (Sandbox Code Playgroud)
基于您的代码的示例可能是:
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();
}
Run Code Online (Sandbox Code Playgroud)
从外部终止正在运行的线程通常是一个坏主意,因为您不知道线程当前所处的状态。它可能需要做一些清理工作,而当它无法做到这一点时你强行关闭它。这就是为什么所有执行此操作的 Thread 方法都被标记为 deprecated。
最好使用可用于进程间通信的众多技术中的一种来向在线程本身中运行的过程发出信号,表明它必须中止其工作并正常退出。一种方法是向abort()
runnable添加一个方法,它会引发一个声明为volatile
. Runnable 的内部循环检查该标志并在该标志被引发时退出(以受控方式)。