JDK线程池和Spring线程池的使用
2023-09-14 09:08:23 时间
JDK线程池和Spring线程池实例,异步调用,可以直接使用 (1)JDK线程池的使用,此处采用单例的方式提供,见示例: public class ThreadPoolUtil { private static int corePoolSize = 5; private static int maximumPoolSize = 10; private static long keepAliveTime = 60L; private static TimeUnit unit = TimeUnit.SECONDS; private static int capacity = 1024; private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("jdk-thread-pool-%d").build(); private static final ExecutorService executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<>(capacity), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); private ThreadPoolUtil () { } public static ExecutorService getExecutorService () { return executorService; } } 在其它地方可以直接这样使用: ThreadPoolUtil.getExecutorService().execute(() -> { System.out.println("test1"); System.out.println("test2"); }) (2)Spring线程池的使用,此处通过配置类的方式配置线程池的相关属性,见示例: @Configuration @EnableAsync public class DocataThreadBeanConfig {private int corePoolSize = 5;private int maxPoolSize = 10;private int queueCapacity = 1024;private String namePrefix = "async-service-task-";
// 上述属性可以通过@Value来读取配置值 @Bean(name = "asyncServiceTaskExecutor") public TaskExecutor asyncServiceExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 设置核心线程数 executor.setCorePoolSize(corePoolSize); // 设置最大线程数 executor.setMaxPoolSize(maxPoolSize); // 设置队列容量 executor.setQueueCapacity(queueCapacity); // 设置线程活跃时间(秒) executor.setKeepAliveSeconds(60); // 设置默认线程名称 executor.setThreadNamePrefix(namePrefix); // 设置拒绝策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); executor.initialize();; return executor; } } 在其它文件中需要这样使用: @Resource(name="asyncServiceTaskExecutor") private ThreadPoolTaskExecutor asyncServiceTaskExecutor; 不要直接使用@Autowired,否则会提示失败的 @Autowired private ThreadPoolTaskExecutor asyncServiceTaskExecutor;
------20191128闪
相关文章
- spring boot: 热部署(一) run as – java application (spring-loader-1.2.4.RELEASE.jar)
- Spring AOP源码分析(二)JDK动态代理和CGLIB介绍
- 将Spring Boot程序打包成docker镜像
- Spring Bean的获取与实例化
- Inside Spring - learning notes - Jerry Wang的Spring学习笔记
- spring常用的一些注解以及注解注入总结
- Spring AOP中的动态代理主要有两种方式,JDK动态代理和CGLIB动态代理:
- 【Spring】Spring是什么?
- Spring 官方证实:框架爆大漏洞,JDK 9 及以上版本均受影响
- 毕业设计 Spring Boot的汽车租赁系统(含源码+论文)
- 通过BeanPostProcessor理解Spring中Bean的生命周期
- spring cloud: 使用consul来替换eureka
- spring cloud 项目
- Spring Cloud使用Feign调用服务接口
- Spring JDK动态代理(附带实例)
- 【Spring Boot】SpringBoot设计了哪些可拓展的机制?