根据有关执行人中newFixedThreadPool的文档,我发现



在运行代码时,我检测到容量为5的固定大小的threadPool随着时间的流逝不断生成线程,就像pool-1-thread-3212一样,它应该是pool-1-thread-5 or less
所以我想知道ExecutorService何时确定其线程之一失败并启动新线程。

谁能指导我为什么会这样?

最佳答案

如果未正确实现异常处理,则线程将死亡,具体取决于将任务提交给ExeuctorService的方式。

由于您使用的是FixedThreadPool,因此必须在线程死亡的情况下保持固定数量的线程。

如果使用execute而不是submit,则线程将在未处理的异常情况下死亡。

使用execute()模拟异常和线程死亡的示例代码

导入java.util.concurrent。*;

import java.util.*;

public class ThreadDeath{
    public ThreadDeath()
    {
        System.out.println("creating service");
        ExecutorService service = Executors.newFixedThreadPool(2);
        for ( int i=0; i < 5; i++){
            service.execute(new Runnable(){
                     public void run(){
                        int a=4, b = 0;
                        System.out.println("Thread Name before divide by zero:"+Thread.currentThread().getName());
                        System.out.println("a and b="+a+":"+b);
                        System.out.println("a/b:"+(a/b));

                     }
                });
        }
        service.shutdown();
    }
    public static void main(String args[]){
        ThreadDeath test = new ThreadDeath();
    }
}

现在检查输出中的线程名称:
creating service
Thread Name before divide by zero:pool-1-thread-1
Thread Name before divide by zero:pool-1-thread-2
a and b=4:0
a and b=4:0
Exception in thread "pool-1-thread-1" Thread Name before divide by zero:pool-1-thread-3Exception in thread "pool-1-thread-2"
a and b=4:0
Thread Name before divide by zero:pool-1-thread-4
Exception in thread "pool-1-thread-3" a and b=4:0java.lang.ArithmeticException: / by zero

Thread Name before divide by zero:pool-1-thread-5

现在,只需在提交execute任务时将submit替换为Runnable。该异常将被吞噬,并且输出如下所示:(由于FixedThreadPool的大小为2,因此您只能看到两个线程)
creating service
Thread Name before divide by zero:pool-1-thread-1
a and b=4:0
Thread Name before divide by zero:pool-1-thread-2
a and b=4:0
Thread Name before divide by zero:pool-1-thread-1
a and b=4:0
Thread Name before divide by zero:pool-1-thread-2
Thread Name before divide by zero:pool-1-thread-1
a and b=4:0
a and b=4:0

有关线程创建的更多详细信息,请引用以下grepcode链接:
private boolean addWorker(Runnable firstTask, boolean core)

关于java - ExcecutorService何时在执行过程中失败?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38713938/

10-10 11:53