Java线程池的使用

用于大数据量的导出报表、远程请求处理数据量同步等等

日常项目中可以定义多个线程池,如:报表导出使用的线程池 或 大数据量操作时使用(在配合webSocket通知前端,再或者大文件上传的线程池)

导出大数据量Excel文件时,单个xlsx文件最大只能存储一百多万的数据行,假设有2000万的数据我们日常清空必定导出多个Excel文件,此时就可以使用本文章的案例。

自定义线程池

    private Logger logger = LoggerFactory.getLogger(InitBeanConfig.class);

    @Bean
    public ExecutorService callbackThreadPool() {
        ThreadFactory factory = new ThreadFactoryBuilder()
                .setUncaughtExceptionHandler((t, e) -> logger.error(t.getName() + " excute error:", e))
                .setNameFormat("callback-pool-%d").build();
        int corePoolSize = 3;
        int maxPoolSize = 4;
        long keepAliveTime = 5;
        ExecutorService pool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MINUTES,
                new ArrayBlockingQueue(100000), factory, new ThreadPoolExecutor.CallerRunsPolicy());
        return pool;
    }

使用方法

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("thread")
public class ThreadPoolController {

    @Resource
    private ExecutorService callbackThreadPool;

    @GetMapping
    public Object thread(){
        callbackThreadPool.execute(() -> {
            for (int i = 0 ;i < 1000000;){
                System.out.println(i);
                System.out.println(Thread.currentThread().getName());
            }
        });
        return 1;
    }
}

你可能感兴趣的:(后端笔记,java,开发语言,后端)