How to quickly implement asynchronous calling methods in java
What is asynchronous programming
Before implementing asynchronous calls, let's understand what is asynchronous programming? What scenarios are applicable and so on.
We all know that in traditional synchronous programming, when an operation starts to execute, the program blocks and waits for the operation to complete before continuing to execute subsequent code . This blocking waiting method may lead to a decrease in program response performance, because other tasks cannot be processed at the same time during the waiting process. This kind of obviousness is useless in some time-consuming scenarios, and even affects the experience.
Such as file reading and writing, network requests, or computing-intensive tasks, such as face fusion special effects, etc., are all time-consuming operations. At this time, we need asynchronous programming.
Asynchronous programming does not block the execution of the program. It submits time-consuming operations to background threads or other execution environments and returns immediately so that the program can continue to perform other tasks . When the time-consuming operation is completed, the main thread will be notified through callback, event or polling, etc., and the main thread will process the operation result or execute the corresponding callback function.
CompletableFuture
Today we will learn about CompletableFuture
it, a powerful asynchronous programming tool introduced by Java 8, which can be used to implement complex asynchronous operations and handle chained asynchronous tasks.
From this JDK, it can be seen that it not only implements Future
the interface, but also has all the features of Future, such as using get()
the method to obtain the return value, etc.
It also implements CompletionStage
the interface and provides rich methods to manage the execution of asynchronous tasks and process task results. And there are more than 40 of these interfaces, which is enough for our daily use.
1. supplyAsync
1. CompletableFuture<T> supplyAsync(Supplier<? extends T> supplier)
This method accepts a Supplier functional interface as a parameter, which is used to execute an asynchronous task with a return value. Returns an CompletableFuture
object that can be used to obtain the execution result of an asynchronous task.
parameter:
Supplier
: A no-argument functional interface for providing the result of an asynchronous task.
2. runAsync
2、CompletableFuture<Void> runAsync(Runnable runnable)
This method accepts a Runnable functional interface as a parameter, which is used to execute an asynchronous task with no return value. Returns an CompletableFuture
object that can be used to wait for an asynchronous task to complete.
Parameters:
Runnable
: A functional interface without parameters, used to perform asynchronous tasks.
3. thenApply
3、CompletableFuture<T> thenApply(Function<? super T,? extends U> function)
This method accepts a Function functional interface as a parameter, which is used to process the result of CompletableFuture and return a new CompletableFuture object.
Parameters:
Function
: A functional interface that takes one parameter to transform or process the result of the asynchronous task.
4. thenAccept
4、CompletableFuture<Void> thenAccept(Consumer<? super T> consumer)
This method accepts a Consumer functional interface as a parameter, which is used to CompletableFuture
consume the result, and has no return value .
parameter:
Consumer
: A functional interface with one parameter for consuming the result of an asynchronous task.
5. thenRun
5、CompletableFuture<Void> thenRun(Runnable action)
This method accepts a Runnable functional interface as a parameter, which is used to perform the specified operation after the result of the CompletableFuture is completed, and has no return value.
Parameters:
BiFunction
: A functional interface with two parameters used to combine the results of two CompletableFutures.
6. thenCombine
6、CompletableFuture<U> thenCombine(CompletionStage<? extends V> other, BiFunction<? super T,? super U,? extends V> fn)
This method accepts an CompletionStage
object and a BiFunction
functional interface as parameters, which is used to wait for the completion of the current CompletableFuture
and another CompletionStage
object, combine the results, and return a new CompletableFuture
object.
parameter:
CompletionStage
: Represents the execution status of an asynchronous task.
return value:
CompletableFuture<T>
: Indicates the result of an asynchronous task, through which the execution result of the asynchronous task can be obtained.CompletableFuture<Void>
: Indicates the result of an asynchronous task with no return value.
java demo
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 使用supplyAsync方法创建一个CompletableFuture对象来执行有返回值的异步任务
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println("异步任务正在执行");
return 100;
});
// 使用thenApply方法对异步任务的结果进行处理,并返回新的CompletableFuture对象
CompletableFuture<String> processedFuture = future.thenApply(result -> {
System.out.println("对异步任务结果进行处理");
return "处理后的结果:" + result * 2;
});
// 使用get方法阻塞当前线程,并获取异步任务的执行结果
String result = processedFuture.get();
System.out.println(result);
}
}
异步任务正在执行
对异步任务结果进行处理
处理后的结果:200