gpt4 book ai didi

java - 如何终止具有 'Busy' 个线程的 threadPoolExecutor?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:19:17 26 4
gpt4 key购买 nike

我的问题有点复杂。让我试着彻底解释一下,但如果您需要更多细节,请随时问我,我会添加它们。

我最近(通过实验)了解到,如果一个线程连续工作,比如 while(true) 循环中的整数运算,中断线程对其没有影响。线程像什么都没发生一样继续进行。

现在,使用 shutDown() 或 shutDownNow() 方法终止 ThreadPoolExecutors。我检查了这些方法的代码,它们使用 interrupt() 调用来终止线程。那么,如果所有线程都在忙着做事,执行者将如何被杀死?它是如何被杀死的,例如当我们在 spring 应用程序中使用它时。

一个这样的执行者看起来像:

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
public static void main(String[] a) {
ExecutorService ex = Executors.newFixedThreadPool(50);
for (int i = 0; i < 50; i++) {
ex.execute(new Thread() {
public void run() {
try {
File f = File.createTempFile("testfile", "txt");
while (true) {
f.canRead();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
});
}

ex.shutdown();
ex.shutdownNow();
}
}

最佳答案

要回答您的主要问题,除非明确告知 JVM 通过 System.exit() 退出,否则不会。

对于应该是可中断的长时间运行的操作,实现有责任通过 Thread.currentThread().isInterrupted() 检查中断标志。

例如:

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
public static void main(String[] a) {
ExecutorService ex = Executors.newFixedThreadPool(50);
for (int i = 0; i < 50; i++) {
ex.execute(new Runnable() {
public void run() {
try {
File f = File.createTempFile("testfile", "txt");
while (!Thread.currentThread().isInterrupted()) {
f.canRead();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
});
}

ex.shutdown();
ex.shutdownNow();
}
}

另请注意,创建 Thread 的实例仅用作 Runnable 是不合适的。这样做会产生一种间接性,可能会让更天真的程序员感到困惑。

关于java - 如何终止具有 'Busy' 个线程的 threadPoolExecutor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4675956/

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