@Slf4j
@Configuration
@EnableAsync
public class ExecutorConfig {
@Bean
public Executor asyncCopyServiceExecutor() {
log.info("start async copy from ops to dest container Executor......");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(10);
//配置最大线程数
executor.setMaxPoolSize(10);
//配置队列大小
executor.setQueueCapacity(5000);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("async-copy-service-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
定义线程池的几种方式
package com.example.chaoming.exercise.jdk.juc;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.Test;
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
/**
* 线程池的创建与定义
*/
public class ThreadPoolTest {
/**
* 创建cache线程池
*/
@Test
public void createNewCachedThreadPool () {
// 无界线程池
ExecutorService executorService = Executors.newCachedThreadPool();
// 构造器
new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
/**
* 创建Fixed线程池
*/
@Test
public void createNewFixedThreadPool () {
// 固定长度线程池
ExecutorService executorService1 = Executors.newFixedThreadPool(100);
// 构造器
new ThreadPoolExecutor(100, 100,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
/**
* 创建Fixed线程池
*/
@Test
public void createNewSingleThreadExecutor () {
// 固定长度线程池
ExecutorService executorService1 = Executors.newSingleThreadExecutor();
// 构造器
// 思考一下 keepAlivetime = 0 ???会怎样
new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
/**
* 创建Fixed线程池
*/
@Test
public void createNewScheduledThreadPool () {
// 固定长度线程池
ExecutorService executorService1 = Executors.newScheduledThreadPool(5);
// 构造器
// super(5, Integer.MAX_VALUE, 0, NANOSECONDS,
// new ScheduledThreadPoolExecutor.DelayedWorkQueue());
}
private ExecutorService spiderExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2
, Runtime.getRuntime().availableProcessors() * 10
//当线程数大于核心时,多于的空闲线程最多存活时间
, 0
, TimeUnit.SECONDS
//无界阻塞队列,当添加速度大于移除速度会内存溢出
, new LinkedBlockingQueue<>(1024)
// 定义线程名称
, new ThreadFactoryBuilder().setNameFormat("spider-pool-%d").build()
, new ThreadPoolExecutor.AbortPolicy());
}