1 回答
TA贡献1946条经验 获得超3个赞
如果我理解正确,你想要这样的东西:
ExecutorService executorService = Executors.newFixedThreadPool(4); // TODO: proper number of threads
Future<Integer> future1 = executorService.submit(() -> callService1()); // TODO: proper type and method
Future<String> future2 = executorService.submit(() -> callService2()); // TODO: proper type and method
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.MINUTES); // TODO: proper timeout
Integer result1 = future1.get(); // TODO: proper type
String result2 = future2.get(); // TODO: proper type
解释:
上面的代码创建了一个
ExecutorService
有 4 个线程的线程,您可以向其中提交所有任务(即调用微服务)然后你打电话
ExecutorService.shutdown
(不允许更多的任务提交)和ExecutorService.awaitTermination
(等到所有任务完成)最后,你调用
Future.get
所有的期货来得到结果请注意,如果任务在执行过程中抛出异常,则调用
Future.get
将抛出一个ExecutionException
包装任务抛出的异常
添加回答
举报