如何正确的使用JDK线程池和Spring线程池
这期内容当中小编将会给大家带来有关如何正确的使用JDK线程池和Spring线程池,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
JDK线程池和Spring线程池实例,异步调用,可以直接使用
(1)JDK线程池的使用,此处采用单例的方式提供,见示例:
publicclassThreadPoolUtil{ privatestaticintcorePoolSize=5; privatestaticintmaximumPoolSize=10; privatestaticlongkeepAliveTime=60L; privatestaticTimeUnitunit=TimeUnit.SECONDS; privatestaticintcapacity=1024; privatestaticThreadFactorynamedThreadFactory=newThreadFactoryBuilder().setNameFormat("jdk-thread-pool-%d").build(); privatestaticfinalExecutorServiceexecutorService=newThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, newLinkedBlockingQueue<>(capacity), namedThreadFactory, newThreadPoolExecutor.AbortPolicy()); privateThreadPoolUtil(){ } publicstaticExecutorServicegetExecutorService(){ returnexecutorService; } }
在其它地方可以直接这样使用:
ThreadPoolUtil.getExecutorService().execute(()->{ System.out.println("test1"); System.out.println("test2"); } )
(2)Spring线程池的使用,此处通过配置类的方式配置线程池的相关属性,见示例:
@Configuration @EnableAsync publicclassDocataThreadBeanConfig{ privateintcorePoolSize=5; privateintmaxPoolSize=10; privateintqueueCapacity=1024; privateStringnamePrefix="async-service-task-"; //上述属性可以通过@Value来读取配置值 @Bean(name="asyncServiceTaskExecutor") publicTaskExecutorasyncServiceExecutor(){ ThreadPoolTaskExecutorexecutor=newThreadPoolTaskExecutor(); //设置核心线程数 executor.setCorePoolSize(corePoolSize); //设置最大线程数 executor.setMaxPoolSize(maxPoolSize); //设置队列容量 executor.setQueueCapacity(queueCapacity); //设置线程活跃时间(秒) executor.setKeepAliveSeconds(60); //设置默认线程名称 executor.setThreadNamePrefix(namePrefix); //设置拒绝策略 executor.setRejectedExecutionHandler(newThreadPoolExecutor.CallerRunsPolicy()); //等待所有任务结束后再关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); executor.initialize(); ; returnexecutor; } }
在其它文件中需要这样使用:
@Resource(name="asyncServiceTaskExecutor") privateThreadPoolTaskExecutorasyncServiceTaskExecutor;
不要直接使用@Autowired,否则会提示失败的
@Autowired privateThreadPoolTaskExecutorasyncServiceTaskExecutor;
上述就是小编为大家分享的如何正确的使用JDK线程池和Spring线程池了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注恰卡编程网行业资讯频道。
推荐阅读
-
Linux中如何安装和使用 Java 开发环境
-
jdk8中怎么使用stream实现对象属性的合并
jdk8中怎么使用stream实现对象属性的合并这篇“jdk8中怎...
-
JDK6动态编译的方法是什么
JDK6动态编译的方法是什么这篇文章主要介绍“JDK6动态编译的方...
-
JDK里的经典设计模式有哪些
JDK里的经典设计模式有哪些本篇内容介绍了“JDK里的经典设计模式...
-
jdk中try-with-resources怎么用
jdk中try-with-resources怎么用这篇文章主要介绍...
-
java小工具都有哪些
java小工具都有哪些java小工具都有哪些,很多新手对此不是很清...
-
JDK和CGLib动态代理怎么实现
JDK和CGLib动态代理怎么实现本篇内容介绍了“JDK和CGLi...
-
关于JDK+Tomcat+eclipse+MyEclipse的配置方法,看这篇够了
关于JDK+Tomcat+eclipse+MyEclipse的配置方法,看这篇够了Eclipse最新版本EclipseNeo...