如何停止java执行器类中的所有可运行线程?

2024-04-17

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执行器类的方法:

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。这是我的代码流程:

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

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


The shutDown() http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdown%28%29方法只是阻止安排额外的任务。相反,你可以打电话shutDownNow() http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdownNow%28%29并检查线程是否中断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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何停止java执行器类中的所有可运行线程? 的相关文章

随机推荐