• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

JDK线程池和Spring线程池的使用实例解析

java 搞代码 4年前 (2022-01-05) 55次浏览 已收录 0个评论

这篇文章主要介绍了JDK线程池和Spring线程池的使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了JDK线程池和Spring线程池的使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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 namedTh<mark style="color:transparent">来源gaodaimacom搞#代%码网</mark>readFactory = 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;

以上就是JDK线程池和Spring线程池的使用实例解析的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:JDK线程池和Spring线程池的使用实例解析

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址