一個月后,我只在 Javascript/Typescript 上遇到了一些麻煩。
例如,讓我們看看這個片段:
@Test
public void testAsync(){
CompletableFuture.supplyAsync(()->{
try{
Thread.sleep(10000);
System.out.println("After some seconds");
}catch(InterruptedException exc){
return "Fail";
}
return "Done";
}).thenAccept(s->System.out.println(s)).join();
System.out.println("should write before After some seconds statement");
}
我期待最后一個 system.out.println 在 CompletableFuture 之前運行,但它等待 Future 的完成。
所以,我得到的是:“幾秒鐘后”“完成”“應該在幾秒鐘后宣告之前寫”
我想要什么:“應該在幾秒鐘后宣告之前寫”“幾秒鐘后”“完成”
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
將未來存盤在變數中,列印陳述句,然后join()等待結果:
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10000);
System.out.println("After some seconds");
} catch (InterruptedException exc) {
return "Fail";
}
return "Done";
}).thenAccept(s -> System.out.println(s));
System.out.println("should write before After some seconds statement");
future.join();
至于解釋,該.join()方法的javadoc說:
完成時回傳結果值,如果例外完成則拋出(未經檢查的)例外
這意味著,如果您呼叫.join()chained to thenAccept(),則意味著您將首先等待supplyAsync()to 結束,然后將thenAccept(),并通過join().
因此,您將System.out.println("should write before After some seconds statement");在所有操作完成后到達您的位置。
如果您的目標是在完成測驗之前等待未來,那么您應該join()使用主執行緒呼叫列印后,而不是之前。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477791.html
