如何在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者类的run方法:

 public void run() { try { Thread.sleep(20 * 1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }} 

在这里等待20秒,但是当我运行代码时它抛出一个exception:

 java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) 

我无法在Java Executor class关闭并发线程破坏。 这是我的代码流程:

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

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

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(); } 

从外部终止正在运行的线程通常是一个坏主意,因为你不知道线程当前所处的状态。它可能需要进行一些清理,并且当它不可能做到时你强行关闭它。 这就是为什么执行该操作的所有Thread方法都被标记为已弃用的原因 。

最好使用许多可用于进程间通信的技术之一来表示线程本身运行的过程,它必须中止其工作并正常退出。 一种方法是向runnable添加一个abort()方法,它会引发一个声明为volatile的标志。 Runnable的内部循环检查该标志并在引发该标志时以受控方式退出。