gpt4 book ai didi

java - 为什么 ExecutorService.shutdownNow 方法不能停止线程

转载 作者:搜寻专家 更新时间:2023-10-31 08:29:49 25 4
gpt4 key购买 nike

package util.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ShutdownDemo {
public static void main(String[] args) throws InterruptedException{
ExecutorService executor = Executors.newSingleThreadExecutor();

executor.execute(new Runnable(){

@Override
public void run() {
while(true){
System.out.println("-- test --");
}
}

});

TimeUnit.SECONDS.sleep(3);

executor.shutdownNow();
}
}

我已经调用了shutdownNow方法,为什么console继续打印“--test--”??

最佳答案

查看 JavaDoc 中的 Thread.stop() 了解完整原因:

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#stop()

从本质上讲,您的线程必须自行停止,以使您的程序保持安全。仅仅停止线程会使程序处于不可预测的状态,在这种状态下,线程拥有的锁不会被释放,资源也不会返回给操作系统。最终让您的程序面临死锁、无法释放的内存泄漏,并可能影响操作系统的稳定性。如果您使用 C 或任何其他语言,这实际上没有任何不同,因为停止 native 线程会遇到这些问题。请记住,线程不是进程,它们与其他线程共享内存和状态,因此它们必须行为和合作。

Java 致力于中断线程而不是杀死线程,因此在编写线程时线程必须符合此模型。因此, while(true) 在您的程序中是不好的做法。相反,您需要查看您的线程是否已被中断,并自行关闭。使用 Thread.sleep 并正确处理 InterruptedException。或者在你的 while 循环中检查 Thread.isInterrupted()。

关于java - 为什么 ExecutorService.shutdownNow 方法不能停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4446395/

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