springboot中自定义线程池的创建

407 阅读1分钟

springboot 中初始化自定线程池的代码笔记,ThreadPoolExecutorBean类


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
public  class ThreadPoolExecutorBean {

    /**
     * 利用ThreadFactory修改线程名称
     */
    private static class TaskExecutionThreadFactory implements ThreadFactory {
        private AtomicInteger threadNum = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("自定义线程名称-" + threadNum.incrementAndGet());
            return t;
        }
    }

    /**
     * 初始化线程池
     */
    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,
        30,
        0,
        TimeUnit.SECONDS,
        new LinkedBlockingQueue<Runnable>(),
        new TaskExecutionThreadFactory(),
        new ThreadPoolExecutor.CallerRunsPolicy());


    @Bean
    public ThreadPoolExecutor getThreadPoolExecutor(){
        return threadPoolExecutor;
    }
}