使用Spring中的异步多线程来运行并发任务

huangapple go评论99阅读模式
英文:

Using Async multithreading in Spring to run concurrent tasks

问题

  1. 我对Spring非常新我正在尝试从两个单独的类中调用两个方法多次调用每个方法并且我希望每次调用都会启动一个新线程以便它们并发运行这是我编写的代码
  2. 主类
  3. @SpringBootApplication
  4. @EnableOAuth2Client
  5. @EnableAsync
  6. public class MainApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(MainApplication.class, args);
  9. }
  10. }
  11. class SomeOtherClass {
  12. for (int i = 0; i < 100; i++) {
  13. Class1 class1 = new Class1();
  14. class1.method1(//它的参数);
  15. }
  16. // 做其他事情
  17. // ...
  18. // 方法2将使用方法1的副作用,因此理想情况下,下一个for循环应该在前一个for循环结束后才开始
  19. for (int i = 0; i < 50; i++) {
  20. Class2 class2 = new Class2();
  21. class2.method2(//它的参数);
  22. }
  23. }
  1. public Class1 {
  2. @Async("threadPoolTaskExecutor")
  3. public void method1() throws Exception {
  4. LOGGER.info("在{}中运行此方法", Thread.currentThread().getName());
  5. }
  6. }
  1. public Class2 {
  2. @Async("threadPoolTaskExecutor")
  3. public void method2() throws Exception {
  4. LOGGER.info("在{}中运行此方法", Thread.currentThread().getName());
  5. }
  6. }
  1. @Configuration
  2. @EnableAsync
  3. public class ThreadConfig {
  4. @Bean("threadPoolTaskExecutor")
  5. public TaskExecutor threadPoolTaskExecutor() {
  6. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  7. executor.setCorePoolSize(100);
  8. executor.setMaxPoolSize(100);
  9. executor.initialize();
  10. return executor;
  11. }
  12. }

问题是当我运行应用程序时,我只看到一个线程名称打印,这意味着它并未以多线程方式运行。从日志中可以看出,调用是按顺序进行的。通过使用标准Java(Runnable)进行多线程处理,我知道多线程版本应该更快完成。由于我对Spring非常陌生,我不明白我做错了什么。

我已经删除了方法名称和逻辑,但注释和类结构完全相同,因此如果您发现任何问题,请指出。

  1. <details>
  2. <summary>英文:</summary>
  3. I am very new to Spring and I am trying to call two methods from two separate classes a number of times, and I want each invocation to spin a new thread so they run concurrently. This is the code I have:
  4. the main class:
  5. @SpringBootApplication
  6. @EnableOAuth2Client
  7. @EnableAsync
  8. public class MainApplication {
  9. public static void main(String[] args) {
  10. SpringApplication.run(MainApplication.class, args);
  11. }
  12. }

class SomeOtherClass {

for (int i = 0; i < 100; i++) {
Class1 class1 = new Class1();
class1.method1(//its arguments);
}

// doing other things
// ...

// method 2 will use the side effects of method 1, so ideally this next
// for loop should start only after the previous one is over
for (int i = 0; i < 50; i++) {
Class2 class2 = new Class2();
class2.method2(//its arguments);
}

}

public Class1 {

@Async("threadPoolTaskExecutor")
public void method1() throws Exception {
LOGGER.info("Running this in {}", Thread.currentThread().getName());
}

}

public Class2 {

@Async("threadPoolTaskExecutor")
public void method2() throws Exception {
LOGGER.info("Running this in {}", Thread.currentThread().getName());
}

}

@Configuration
@EnableAsync
public class ThreadConfig {

  1. @Bean(&quot;threadPoolTaskExecutor&quot;)
  2. public TaskExecutor threadPoolTaskExecutor() {
  3. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  4. executor.setCorePoolSize(100);
  5. executor.setMaxPoolSize(100);
  6. executor.initialize();
  7. return executor;
  8. }

}

  1. The problem is when I run the application I only see one thread name printing, which means it&#39;s not running in a multithreaded way. Looking at the logs, I can also see the calls are being made sequentially. Having done multithreading using standard Java (Runnable), I know the multithreaded version should finish much faster. Since I am very new to Spring, I do not understand what I am doing wrong.
  2. I have redacted the method names and logic, but the annotations and class structures are exactly thee same, so if you see any problem with that please point that out.
  3. </details>
  4. # 答案1
  5. **得分**: 1
  6. 要使 `method1` `method2` 异步工作,您需要让 Spring 管理 Class1 Class2 的实例。将 `Class1 class1 = new Class1();` 替换为依赖注入。
  7. ```java
  8. @Service
  9. public Class1 {
  10. ...
  11. ```
  12. ```java
  13. @Service
  14. class SomeOtherClass {
  15. @Autowired
  16. Class1 class1;
  17. //...
  18. // 您的循环
  19. ```
  20. 编辑:
  21. 如果您需要在第一个循环中的所有异步执行完成后才执行第二个循环,您可以使用 `Future` 类:
  22. ```java
  23. @Async(...)
  24. public Future<Object> method1() {
  25. ...
  26. return null;
  27. }
  28. ```
  29. ```java
  30. List<Future<Object>> futures = new ArrayList<>();
  31. for (int i = 0; i < 1000; i++) {
  32. futures.add(class1.method1(/*其参数*/));
  33. }
  34. futures.forEach(f -> {
  35. try {
  36. f.get();
  37. } catch (ExecutionException | InterruptedException e) {
  38. e.printStackTrace();
  39. }
  40. });
  41. // 所有 method1 的调用已完成
  42. ```
  43. <details>
  44. <summary>英文:</summary>
  45. To get `method1` and `method2` work asynchronously you have to let Spring manage instances of the Class1 and Class2. Replace `Class1 class1 = new Class1();` with the dependency injection.
  46. ```java
  47. @Service
  48. public Class1 {
  49. ...
  50. ```
  51. ```java
  52. @Service
  53. class SomeOtherClass {
  54. @Autowired
  55. Class1 class1;
  56. //...
  57. // your loops
  58. ```
  59. EDIT:
  60. If you need to perform second loop only after completion of all async executions in the first loop then you can use `Future` class:
  61. ```java
  62. @Async(...)
  63. public Future&lt;Object&gt; method1() {
  64. ...
  65. return null;
  66. }
  67. ```
  68. ```java
  69. List&lt;Future&lt;Object&gt;&gt; futures = new ArrayList&lt;&gt;();
  70. for (int i = 0; i &lt; 1000; i++) {
  71. futures.add(class1.method1(/*its arguments*/));
  72. }
  73. futures.forEach(f -&gt; {
  74. try {
  75. f.get();
  76. } catch (ExecutionException | InterruptedException e) {
  77. e.printStackTrace();
  78. }
  79. });
  80. // all of invocations of method1 are finished
  81. ```
  82. </details>

huangapple
  • 本文由 发表于 2020年10月19日 08:41:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64419735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定