线程池配置第一种
import com.esotericsoftware.minlog.Log;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableScheduling
public class TreadTaskConfig implements SchedulingConfigurer, AsyncConfigurer {
/** 异步处理 */
public void configureTasks(ScheduledTaskRegistrar taskRegistrar){
TaskScheduler taskScheduler = threadPoolTaskScheduler();
taskRegistrar.setTaskScheduler(taskScheduler);
}
SpringUtils.getBean("threadPoolTaskScheduler",TreadConfig.class);
//线程池维护线程的最少数量
@Value("${ThreadPoolTask.poolSize}")
private Integer poolSize;
//允许的空闲时间
@Value("${ThreadPoolTask.awaitTerminationSeconds}")
private Integer awaitTerminationSeconds;
//线程池名称
@Value("${ThreadPoolTask.threadNamePrefix}")
private String threadNamePrefix;
//缓存队列
@Value( "${ThreadPoolTask.waitForTasksToCompleteOnShutdown}")
private Boolean waitForTasksToCompleteOnShutdown;
@Bean(destroyMethod = "shutdown")
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.initialize();
scheduler.setPoolSize(poolSize);
scheduler.setThreadNamePrefix(threadNamePrefix);
scheduler.setAwaitTerminationSeconds(awaitTerminationSeconds);
scheduler.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown);
scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
scheduler.setErrorHandler(throwable -> Log.error("调度任务发生异常", throwable));
return scheduler;
}
/** 异步处理 */
public Executor getAsyncExecutor(){
Executor executor = threadPoolTaskScheduler();
return executor;
}
/** 异步处理 异常 */
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
return new SimpleAsyncUncaughtExceptionHandler();
}
}
yml里的配置
ThreadPoolTask:
poolSize: 20
awaitTerminationSeconds : 60
threadNamePrefix: PersonTask-Pool-1
waitForTasksToCompleteOnShutdown: true
线程池第二种配置
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @Description:
* @author: yingjie.zhang
* @CreateDate: 2019/8/20 11:05
* */
@ComponentScan
public class ThreadConfig {
//线程池维护线程的最少数量
@Value("${ThreaPool.corePoolSize}")
private Integer corePoolSize;
//允许的空闲时间
@Value("${ThreaPool.keepAliveSeconds}")
private Integer keepAliveSeconds;
//线程池维护线程的最大数量
@Value("${ThreaPool.maxPoolSize}")
private Integer maxPoolSize;
//缓存队列
@Value( "${ThreaPool.queueCapacity}")
private Integer queueCapacity;
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
executor.setRejectedExecutionHandler(callerRunsPolicy);
executor.initialize();
return executor;
}
}
yml配置
ThreaPool:
corePoolSize: 20
keepAliveSeconds: 200
maxPoolSize: 10
queueCapacity: 20
线程池配置注意注解的使用 注解使用错误也会导致线程池能使用
在需要使用的地方直接注入使用即可
@Autowired
private TaskExecutor taskExecutor;
测试案例
import org.junit.Test;
import org.junit.runner.RunWith;
import org.python.jline.internal.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.task.TaskExecutor;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class LoanafterApplicationTests {
@Autowired
private TaskExecutor taskExecutor;
public static <T> List<List<T>> averageAssign(List<T> source,int n){
List<List<T>> result=new ArrayList<List<T>>();
//(先计算出余数)
int remaider=source.size()%n;
//然后是商
int number=source.size()/n;
//偏移量
int offset=0;
for(int i=0;i<n;i++){
List<T> value=null;
if(remaider>0){
value=source.subList(i*number+offset, (i+1)*number+offset+1);
remaider--;
offset++;
}else{
value=source.subList(i*number+offset, (i+1)*number+offset);
}
result.add(value);
}
return result;
}
@Test
public void contextLoads() {
List<Integer> integers=new ArrayList<>();
for (int x=0;x<=1400;x++){
integers.add(1);
integers.add(2);
integers.add(3);
integers.add(4);
integers.add(5);
integers.add(6);
integers.add(7);
integers.add(8);
integers.add(9);
integers.add(10);
integers.add(11);
integers.add(12);
integers.add(13);
integers.add(14);
integers.add(15);
}
System.out.println(1);
List<List<Integer>> lists=averageAssign(integers, 10);
System.out.println(lists);
Log.info(lists.size());
System.out.println(lists.size());
for (int j = 0; j <lists.size(); j++) {
List<Integer> lisrrr=lists.get(j);
if(lisrrr!=null) {
taskExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println(lisrrr);
System.err.println(Thread.currentThread().getName());
System.out.println(System.currentTimeMillis());
// try {
// threadPoolTaskScheduler.wait(3000);
//
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
});
}
}
}
}