gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 19:56:45 24 4
gpt4 key购买 nike

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 中编写
  • executor 等待 10 秒完成任务。
  • 如果任务已完成,则可运行线程也将终止。
  • 如果任务未在 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();
}

关于java - 如何停止 java 执行程序类中的所有可运行线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15900387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com