执行期间ExcecutorService何时失败?

时间:2016-08-02 07:13:12

标签: java multithreading threadpool executorservice

根据有关Executors中newFixedThreadPool的文档,我找到了

  

如果任何线程在执行之前由于执行失败而终止   关闭,如果需要执行,新的将取代它   后续任务。

当我运行我的代码时,我检测到我的固定大小的threadPool,容量为5,随着pool-1-thread-3212时间的推移生成线程,假设为pool-1-thread-5 or less

所以我想知道ExecutorService什么时候决定其中一个线程失败并启动新线程。

有人能指导我发生这种情况的原因吗?

1 个答案:

答案 0 :(得分:2)

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

由于您使用FixedThreadPool,因此在线程死亡时必须保留固定数量的线程。

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

用于模拟异常的示例代码&使用execute()

线程死亡

import 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)