springboot自义定线程池
在boot项目中添加一个自定义线程池的配置
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ThreadPoolExecutor; @Configuration public class ThreadPoolConfig { @Bean public ThreadPoolTaskExecutor myThreadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //此方法返回可用处理器的虚拟机的最大数量; // int core = Runtime.getRuntime().availableProcessors(); int core = 30; //设置核心线程数 executor.setCorePoolSize(core); //设置最大线程数 executor.setMaxPoolSize(core * 10 + core); //除核心线程外的线程存活时间 executor.setKeepAliveSeconds(3); //缓冲队列 executor.setQueueCapacity(core); executor.setThreadNamePrefix("thread-execute"); //设置拒绝策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor; }
在启动类上添加@EnableAsync注解开启多线程
方法上面@Async("myThreadPoolTaskExecutor") 指定使用那个线程池配置,不然会使用spring默认的线程池
也可以自己在使用线程时指定对应的线程池,CompletableFuture这个工具包提供方法还是挺多,不过这个就需要慢慢去探索啦!
public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> { int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } return sum; },myThreadPoolTaskExecutor);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1;
}, myThreadPoolTaskExecutor);
CompletableFuture.allOf(future1, future2);
System.out.println(future1.get() + future2.get());
}