简体   繁体   English

Java Spring 如何进行多线程操作并等待完成

[英]Java Spring How to multithread operations and wait for completion

So I have a get operation where a user supplys a list of items.所以我有一个 get 操作,用户提供一个项目列表。 For each item in the list I need to make an API call which is what takes the most time in my application.对于列表中的每个项目,我需要进行 API 调用,这是我的应用程序中花费最多的时间。

Lets say the flow is List -> Operation A -> Operation B ( API Call ) -> Operation C假设流程是 List -> Operation A -> Operation B ( API Call ) -> Operation C

So instead of processing all the items in the list sequentially, I was thinking if I could create multiple threads.因此,我不是按顺序处理列表中的所有项目,而是考虑是否可以创建多个线程。 All the threads would have to finish Operation B before Operation C starts.所有线程都必须在操作 C 开始之前完成操作 B。 Operations A and C don't need to be multithreaded.操作 A 和 C 不需要是多线程的。

Is there a straightforward way to do this?有没有一种简单的方法可以做到这一点?

You could try to use CompletableFuture for this, something along the lines of:您可以尝试为此使用CompletableFuture ,类似于:

   ExecutorService executorService = Executors.newFixedThreadPool(3);

   CompletableFuture<?>[] all =
   youList.stream()
          .map(x -> CompletableFuture.supplyAsync(() -> operationA(x))
                       .thenApplyAsync(YourClass::operationB)
                       .thenApplyAsync(YouClass::operationC))
            .toArray(x -> new CompletableFuture[0]);

    CompletableFuture.allOf(all);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM