Spring Boot配置多线程(创建线程池、创建线程)

超、凢脫俗 2022-09-10 08:22 497阅读 0赞

1 Maven依赖

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. </dependency>

2 AsyncConfig

多线程配置类。

  1. package com.config;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
  6. import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
  7. import org.springframework.beans.factory.DisposableBean;
  8. import org.springframework.beans.factory.InitializingBean;
  9. import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.context.annotation.Configuration;
  12. import org.springframework.core.task.AsyncTaskExecutor;
  13. import org.springframework.scheduling.annotation.AsyncConfigurer;
  14. import org.springframework.scheduling.annotation.EnableAsync;
  15. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  16. import java.util.concurrent.Callable;
  17. import java.util.concurrent.Executor;
  18. import java.util.concurrent.Future;
  19. /**
  20. * 多线程配置类
  21. */
  22. @Configuration
  23. @EnableAsync
  24. @Slf4j
  25. public class AsyncConfig implements AsyncConfigurer {
  26. private final TaskExecutionProperties taskExecutionProperties;
  27. public AsyncConfig(TaskExecutionProperties taskExecutionProperties) {
  28. this.taskExecutionProperties = taskExecutionProperties;
  29. }
  30. /**
  31. * 创建线程池
  32. *
  33. * @return
  34. */
  35. @Override
  36. @Bean(name = "taskExecutor")
  37. public Executor getAsyncExecutor() {
  38. log.debug("Creating Async Task Executor");
  39. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  40. //设置核心线程数
  41. executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize());
  42. //设置最大线程数
  43. executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize());
  44. //线程池所使用的缓冲队列
  45. executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity());
  46. // 线程名称前缀
  47. executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix());
  48. return new ExceptionHandlingAsyncTaskExecutor(executor);
  49. }
  50. @Override
  51. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  52. return new SimpleAsyncUncaughtExceptionHandler();
  53. }
  54. public static class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor,
  55. InitializingBean, DisposableBean {
  56. static final String EXCEPTION_MESSAGE = "Caught async exception";
  57. private final Logger log = LoggerFactory.getLogger(ExceptionHandlingAsyncTaskExecutor.class);
  58. private final AsyncTaskExecutor executor;
  59. /**
  60. * <p>Constructor for ExceptionHandlingAsyncTaskExecutor.</p>
  61. *
  62. * @param executor a {@link AsyncTaskExecutor} object.
  63. */
  64. public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {
  65. this.executor = executor;
  66. }
  67. /**
  68. * {@inheritDoc}
  69. */
  70. @Override
  71. public void execute(Runnable task) {
  72. executor.execute(createWrappedRunnable(task));
  73. }
  74. /**
  75. * {@inheritDoc}
  76. */
  77. @Override
  78. public void execute(Runnable task, long startTimeout) {
  79. executor.execute(createWrappedRunnable(task), startTimeout);
  80. }
  81. private <T> Callable<T> createCallable(final Callable<T> task) {
  82. return () -> {
  83. try {
  84. return task.call();
  85. } catch (Exception e) {
  86. handle(e);
  87. throw e;
  88. }
  89. };
  90. }
  91. private Runnable createWrappedRunnable(final Runnable task) {
  92. return () -> {
  93. try {
  94. task.run();
  95. } catch (Exception e) {
  96. handle(e);
  97. }
  98. };
  99. }
  100. /**
  101. * <p>handle.</p>
  102. *
  103. * @param e a {@link Exception} object.
  104. */
  105. protected void handle(Exception e) {
  106. log.error(EXCEPTION_MESSAGE, e);
  107. }
  108. /**
  109. * {@inheritDoc}
  110. */
  111. @Override
  112. public Future<?> submit(Runnable task) {
  113. return executor.submit(createWrappedRunnable(task));
  114. }
  115. /**
  116. * {@inheritDoc}
  117. */
  118. @Override
  119. public <T> Future<T> submit(Callable<T> task) {
  120. return executor.submit(createCallable(task));
  121. }
  122. /**
  123. * {@inheritDoc}
  124. */
  125. @Override
  126. public void destroy() throws Exception {
  127. if (executor instanceof DisposableBean) {
  128. DisposableBean bean = (DisposableBean) executor;
  129. bean.destroy();
  130. }
  131. }
  132. /**
  133. * {@inheritDoc}
  134. */
  135. @Override
  136. public void afterPropertiesSet() throws Exception {
  137. if (executor instanceof InitializingBean) {
  138. InitializingBean bean = (InitializingBean) executor;
  139. bean.afterPropertiesSet();
  140. }
  141. }
  142. }
  143. }

3 AsyncTestService

声明异步方法。

  1. package com.service;
  2. import org.springframework.scheduling.annotation.Async;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class AsyncTestService {
  6. @Async
  7. public void test(int num) {
  8. System.out.print("\tnum=" + num);
  9. }
  10. }

4 调试代码

  1. package com.controller;
  2. import com.service.AsyncTestService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class AsyncController {
  8. @Autowired
  9. private AsyncTestService asyncTestService;
  10. /**
  11. * 测试多线程
  12. */
  13. @GetMapping("/testAsync")
  14. public void testAsync() {
  15. for (int i = 0; i < 100; i++) {
  16. System.out.print("\ti=" + i);
  17. }
  18. for (int j = 0; j < 100; j++) {
  19. asyncTestService.test(j);
  20. }
  21. System.out.print("i=" + 1111);
  22. }
  23. }

5 调试结果

watermark_type_ZHJvaWRzYW5zZmFsbGJhY2s_shadow_50_text_Q1NETiBA5pet5Lic5oCq_size_20_color_FFFFFF_t_70_g_se_x_16

注:

有关调用异步方法创建线程的方式请查看以下博客。

Java 调用@Async异步方法创建线程2种方式(调用外部的异步方法,调用内部的异步方法)_旭东怪的博客-CSDN博客1 Maven依赖 org.projectlombok lombok true <!—hutool工favicon32.icohttps://blog.csdn.net/qq\_38974638/article/details/120348519

发表评论

表情:
评论列表 (有 0 条评论,497人围观)

还没有评论,来说两句吧...

相关阅读

    相关 线】——Callable创建线

        之前小编的博客简单介绍了两种创建线程的方式,随着小编工作过程对这一部分的深入,对这一部分有更深入的理解,也知道其他创建多线程方式,在原来的基础在深入一下! 回顾

    相关 线 线创建

    一简介 线程的使用在java中占有极其重要的地位,在jdk1.4极其之前的jdk版本中,关于线程池的使用是极其简陋的。在jdk1.5之后这一情况有了很大的改观。Jdk1.