我必須與不同的服務器建立多個連接并運行一些命令,我??正在使用 for 呼叫異步方法,但我不知道所有執行緒何時完成以發送其他行程。
uj5u.com熱心網友回復:
您可以使用 包裝@Async方法的結果CompletableFuture。回傳它,以便您可以利用 提供的功能CompletableFuture來實作您的目的。
例如 :
@Service
public class FooService {
@Async
public CompletableFuture<String> process(){
String result = processing();
return CompletableFuture.completedFuture(result);
}
}
和客戶端代碼:
CompletableFuture<String> r1 = fooService.process();
CompletableFuture<String> r2 = fooService.process();
CompletableFuture<String> r3 = fooService.process();
CompletableFuture.allOf(r1,r2,r3).join();
System.out.println("All threads are completed now");
uj5u.com熱心網友回復:
謝謝,我使用了另一個解決方案,我使用了一個集合并使用了一個 for 回圈來查看,例如:
@Async
public Future<Void> executeBla() {
System.out.println("Bla!");
return new AsyncResult<Void>(null);
}
public void executeBlaALotOfTimes() {
long before = System.currentTimeMillis();
Collection<Future<Void>> futures = new ArrayList<Future<Void>>();
for (int i = 0; i<40000; i ) {
futures.add(executeBla());
}
for (Future<Void> future : futures) {
future.get();
}
long after = System.currentTimeMillis();
System.out.println("Time it took for a lot of bla to execute: " (after - before) / 1000.0 " seconds.");
}
我在@Async 中查看此選項可防止執行緒繼續,直到其他執行緒完成
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321729.html
上一篇:異步等待不等待輸出回傳
