CompletableFuture.supplyAsync()什么用法
时间: 2023-10-11 22:28:03 浏览: 61
The `CompletableFuture.supplyAsync()` method is used to create and execute an asynchronous task that returns a result. It takes a `Supplier` functional interface as a parameter, which provides the result of the computation. The method returns a `CompletableFuture` object that represents the result of the computation.
Here is an example code snippet that demonstrates the usage of `CompletableFuture.supplyAsync()` method:
```
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Perform some expensive computation here
return "Result of the computation";
});
// Do some other work while the computation is running in the background
String result = future.get(); // This will block until the computation is complete and return the result
```
In this example, we create a `CompletableFuture` that will execute the computation asynchronously using the default executor. The `get()` method is called on the future to block and wait for the result of the computation. This allows us to perform other work while the computation is running in the background. Once the computation is complete, the result can be obtained from the future.
阅读全文