色空大师 2024-09-05 23:10 采纳率: 42.3%
浏览 36

为什么线程中的异常不会打印异常信息

为什么线程中的异常不会打印异常信息

代码如下

package com.test.pool.service.impl;

import com.test.pool.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;

@Service
@Slf4j
public class TestServiceImpl implements TestService {

    @Resource
    ExecutorService simpleExecutor;
    @Override
    public ResponseEntity sun() {
        simpleExecutor.submit(()->{
            log.info("thread start----");
            try {
                first();
                Thread.sleep(1000);
            }catch (Exception e){
                log.error("sleep error");
            }
            int i = 8/0;
            second();
            third();
        });
        return ResponseEntity.ok("success");
    }

    public void first(){
        log.info("first");
    }

    public void second(){
        log.info("second");
    }

    public void third(){
        log.info("third");
    }
}


线程池配置:

package com.test.pool.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadConfig {

    @Qualifier("simpleExecutor")
    @Bean
    public ThreadPoolExecutor simpleExecutor() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(16,
                16,
                10,
                TimeUnit.MINUTES,
                new SynchronousQueue<>(),
                new CustomizableThreadFactory("simple-pool-"),
                new ThreadPoolExecutor.AbortPolicy());
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        return threadPoolExecutor;
    }
}


运行结果如下:

img


请求两次,除0异常没有打印,为什么?

  • 写回答

1条回答 默认 最新

  • kyle凯尔 2024-09-06 16:43
    关注

    simpleExecutor.submit() 提交的Runnable先包装成Callable,然后又被包装成FutureTask,
    FutureTask在run()的时候把 Callable的run()方法【进行异常捕获】,并设置到了FutureTask的outcome中,进行返回。

    img

    评论

报告相同问题?

问题事件

  • 创建了问题 9月5日