首页 文章

执行期间ExcecutorService何时失败?

提问于
浏览
2

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

如果任何线程由于在关闭之前执行期间的故障而终止,则在需要执行后续任务时将使用新的线程 .

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

所以我想知道ExecutorService何时决定其中一个线程失败并启动新线程 .

任何人都可以指导我发生这种情况的原因吗?

1 回答

  • 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
    

    现在只需在提交 Runnable 任务时将 execute 替换为 submit . 将吞下异常并输出如下:(您只能看到两个线程,因为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)
    

相关问题