如何在``Executor Service``java中处理多线程

问题描述 投票:0回答:1

我正在开发一个解决方案,对于单个客户,我需要调用 API 来获取该客户的员工列表。但这个 API(第三方)一次只能返回 100 名员工。因此,我需要通过每次更改偏移量来调用相同的 API,以获取下一组 100 名员工。目前这是使用单线程处理的,因此检索所有员工(假设 30k)的时间随着员工数量的增加而增加。 而且该应用程序有很多这样的客户。

作为此问题的解决方案,我尝试使用

ExecutorService
实现多线程。通过此解决方案,为客户检索所有员工所需的时间减少了。

问题:

  1. 多个线程(来自多个客户)如何与 Executor Service 一起工作,而 Executor Service 又具有多个线程来调用 API?
  2. 多线程环境中的以下逻辑是否会导致最终用户获得不正确的数据? 示例代码:
  ExecutorService executor = Executors.newFixedThreadPool(2);

  ServiceExecutor executor0 = new ServiceExecutor("0");
  ServiceExecutor executor1 = new ServiceExecutor("100");

  Future result0 = executor.submit(executor0);
  Future result1 = executor.submit(executor1);
   
  List<String> s1 = new ArrayList<>();
  s1.add(result0.get());
  s2.add(result1.get());


java multithreading executorservice
1个回答
0
投票

多个线程(来自多个客户)如何与 Executor Service 一起工作,而 Executor Service 又具有多个线程来调用 API?

执行器可以由零个、一个或多个线程支持。

您不需要其他线程。执行器服务的工作是为您管理线程。

© www.soinside.com 2019 - 2024. All rights reserved.