gpt4 book ai didi

java - 使用 future.cancel() 终止底层线程以重新使用该线程

转载 作者:行者123 更新时间:2023-11-30 03:28:18 26 4
gpt4 key购买 nike

public class TestThreadTerminate {
public static void main(String args[]) throws Exception {
ExecutorService e = Executors.newCachedThreadPool();
Future<Boolean> f = e.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
System.out.println("Step 1!!");
Thread.sleep(5000);
System.out.println("Step 2!!");
Thread.sleep(5000);
System.out.println("Step 3!!");
return true;
}
});
try {
Boolean flag = f.get(1, TimeUnit.SECONDS);
} catch(TimeoutException ex) {
f.cancel(true);
System.out.println("Canceling");
}
System.out.println("FINAL!");
}
}

有了这个,我的输出是

Step 1
Canceling
Final

但是程序很晚才终止。为什么一旦线程中断就会发生这种情况?

如果我删除 f.cancel(true),我的线程将继续运行并打印以下内容:

Step 1
Canceling
Final
Step 2
Step 3

如何终止程序,即终止内部线程?实际上,我想将此线程用于线程池中的其他任务,但这似乎没有发生在这里。

在返回之前将 Thread.currentThread().isInterrupted() 放在所有位置看起来不是一个好主意。

最佳答案

Why does it happen once thread is interrupted?

这是因为您的线程池仍然处于 Activity 状态 - 它可能会接受另一个要执行的可运行/可调用,因此它会等待查看是否发生这种情况,然后再清理池中未使用的线程。

缓存线程池的默认超时为 60 秒 - 这与您所看到的相符吗?

如果您希望它更快地关闭,您应该调用e.shutdown()

关于java - 使用 future.cancel() 终止底层线程以重新使用该线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29663888/

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