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;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。