如何在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.

这是执行者类的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类中关闭并发线程破坏.这是我的代码流程:

>创建一个带有Java执行器类的新线程来运行某些任务,即用MyRunnable编写
>执行者等待10秒钟完成任务.
>如果任务已完成,则runnable线程也会终止.
>如果任务未在10秒内完成,则执行程序类应终止该线程.

除了最后一个场景中的任务终止外,一切正常.我该怎么办?

解决方法:

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();
}
上一篇:java – 如何在FutureTask中捕获异常


下一篇:如何在java中设置Socket写入时间?