共計 610 個字符,預計需要花費 2 分鐘才能閱讀完成。
Java 中實現異步轉同步的方法有多種,下面列舉了幾種常用的方法。
- 使用 CountDownLatch:
CountDownLatch latch = new CountDownLatch(1);
// 異步操作
new Thread(() -> {// 執行異步操作
// ...
// 操作完成后釋放鎖
latch.countDown();}).start();
// 等待異步操作完成
latch.await();
- 使用 Future 和 Callable:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<T> future = executor.submit(new Callable<T>() {public T call() throws Exception {// 執行異步操作
// 返回結果
return result;
}
});
// 阻塞并獲取異步操作的結果
T result = future.get();
- 使用 CompletableFuture:
CompletableFuture<T> future = CompletableFuture.supplyAsync(() -> {// 執行異步操作
// 返回結果
return result;
});
// 阻塞并獲取異步操作的結果
T result = future.join();
以上方法都可以實現異步轉同步,但具體使用哪種方法取決于具體的需求和場景。
丸趣 TV 網 – 提供最優質的資源集合!
正文完