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 {
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;
}
}