gpt4 book ai didi

Java 线程池 : What happens to idle threads

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:55:12 25 4
gpt4 key购买 nike

我想了解 Java 中的多线程。我写了下面的java程序来测试线程池。

public class ThreadPoolTest
{
public static void main(String[] args)
{
ExecutorService executorService = Executors.newFixedThreadPool(5);

for( int i = 0; i < 3; i++ )
{
executorService.submit(new Task(i+1));
}
executorService.shutdown();

}

public static class Task implements Runnable
{
private int taskId;

public Task(int id)
{
taskId = id;
}

@Override
public void run() {
System.out.println("Executing task " + taskId + " performed by " + Thread.currentThread().getName() );
try
{
Thread.sleep(3000);
}
catch(InterruptedException interruptEx)
{
System.out.println(Thread.currentThread().getName() + " got interrupted ");
}
System.out.println("Finished executing task " + taskId );
}
}
}

主线程创建了 executor,它创建了 5 个线程,而我只提交了 3 个任务。之后,我将关闭执行者。当我运行代码时,主线程在子线程之前完成。在这种情况下,JVM 是否负责处理子线程?我还创建了一个有 5 个线程的线程池,但只提交了 3 个任务。主线程退出时,剩下的2个线程会不会被终止?

执行程序服务关闭时实际发生了什么?

最佳答案

来自 ExecutorService#shutdown() 的文档:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

这意味着您提交给执行器的所有作业都将按自己的时间完成,而不会中断或“催促”它们,并且执行器将正确地完成工作线程,但服务既不会接受新作业,也不会它立即终止。

比较 ExecutorService#shutdownNow(),它将尝试尽快终止。

关于Java 线程池 : What happens to idle threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27482337/

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