1 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果我理解正確,你想要這樣的東西:
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
解釋:
上面的代碼創(chuàng)建了一個(gè)
ExecutorService
有 4 個(gè)線程的線程,您可以向其中提交所有任務(wù)(即調(diào)用微服務(wù))然后你打電話
ExecutorService.shutdown
(不允許更多的任務(wù)提交)和ExecutorService.awaitTermination
(等到所有任務(wù)完成)最后,你調(diào)用
Future.get
所有的期貨來(lái)得到結(jié)果請(qǐng)注意,如果任務(wù)在執(zhí)行過(guò)程中拋出異常,則調(diào)用
Future.get
將拋出一個(gè)ExecutionException
包裝任務(wù)拋出的異常
添加回答
舉報(bào)