gpt4 book ai didi

java - 如何强制停止无限循环线程

转载 作者:行者123 更新时间:2023-12-02 05:42:15 26 4
gpt4 key购买 nike

下面是代码片段

ExecutorService executor = Executors.newSingleThreadExecutor();

executor.submit(() -> {
while (true) System.out.println("1");
});
executor.shutdown();
executor.shutdownNow();

有什么方法可以从外部关闭执行器吗? (建议不能改变任务本身)就像linux中的kill -9

最佳答案

请阅读 shutdownNow() 的 javadoc方法。上面说的很清楚了:

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

因此,您需要做的就是更改代码中提交的任务以响应 Thread.interrupt()方法。 IE。您需要更改线路
while (true)

while (true && !Thread.currentTrhead().isInterrupted())
有关更多详细信息,请阅读 Thread class 的 javadoc特别是方法interrupt() , interrupted()isInterrupted()

关于java - 如何强制停止无限循环线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56125319/

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