Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use CompletableFuture

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use CompletableFuture". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use CompletableFuture.

However, the Future mechanism is not so flexible, such as how to use the Future mechanism to describe the serial execution of two tasks, or the parallel execution of two tasks, or only care about the result of the first execution.

To some extent, Future mechanism can not meet the above requirements quickly, so CompletableFuture came into being.

1. Create an asynchronous task public static CompletableFuture supplyAsync (Supplier supplier) public static CompletableFuture supplyAsync (Supplier supplier,Executor executor); public static CompletableFuture runAsync (Runnable runnable); public static CompletableFuture runAsync (Runnable runnable,Executor executor)

The difference between supplyAsync and runAsync is that supplyAsync has a return value, while runAsync has no return value

Constructor with the Executor parameter, threads in the thread pool are used to perform asynchronous tasks (thread pool can refer to the thread pool)

Constructor without the Executor argument, the thread in ForkJoinPool.commonPool () is used to perform asynchronous tasks (Fork/Join framework can refer to parallel flow parallelStream)

1.1 example: use supplyAsync to create an asynchronous task public class Case1 {public static void main (String [] args) throws Exception {CompletableFuture completableFuture=CompletableFuture.supplyAsync (() -) > {try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} return 1 ); / / this method will always block Integer result = completableFuture.get (); System.out.println (result);}} 2. Callback public CompletableFuture whenComplete (BiConsumer other,Runnable action) for asynchronous tasks; public static CompletableFuture allOf (CompletableFuture...) Cfs)

ThenCombine, merge two tasks, two tasks can be executed at the same time, when both are executed successfully, the final BiFunction operation is performed. Where T represents the execution result type of the first task, U represents the execution result type of the second task, and V represents the merged result type

The usage of thenAcceptBoth and thenCombine features are very similar, except that thenAcceptBoth makes a consumption and does not return a value.

RunAfterBoth, after both tasks are completed, but do not care about their return structure, and then execute a Runnable.

AllOf, when all tasks are completed, return a CompletableFuture

4.1 example: merge tasks package com.qcy.testCompleteableFuture; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; / * * @ author qcy * @ create using thenCombine 17:40:44 * / public class Case5 {public static void main (String [] args) throws Exception {CompletableFuture cf1 = CompletableFuture.supplyAsync (()-> {System.out.println ("Task 1 start") Try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println (Task 1 ends); return 2;}) CompletableFuture cf2 = CompletableFuture.supplyAsync (()-> {System.out.println ("Task 2 starts"); try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("Task 2 ends"); return 3 }); CompletableFuture completableFuture = cf1.thenCombine (cf2, (result1, result2)-> result1 * result2); System.out.println ("calculation result:" + completableFuture.get ());}}

Output:

You can see that the two tasks are indeed executed at the same time.

Of course, after proficiency, directly use the chain operation, the code is as follows:

Package com.qcy.testCompleteableFuture; import java.util.concurrent.CompletableFuture; / * * @ author qcy * @ create, 2020-09-07 17:40:44 * / public class Case6 {public static void main (String [] args) throws Exception {CompletableFuture completableFuture = CompletableFuture.supplyAsync (()-> {System.out.println ("Task 1 begins"); try {Thread.sleep (3000) } catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("Task 1 ends"); return 2;}) .thenCombine (CompletableFuture.supplyAsync (())-> {System.out.println ("Task 2 starts"); try {Thread.sleep (2000) } catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("Task 2 ends"); return 3;}), (result1, result2)-> result1 * result2); System.out.println ("calculation result:" + completableFuture.get ());}} 5. The task is executed at the same time, and only the first completed task public CompletableFuture applyToEither (CompletionStage other,Runnable action); public static CompletableFuture anyOf (CompletableFuture...) Cfs)

ApplyToEither, the latest task is executed and its result is Function, where T is the first task result type and U is the last output type.

AcceptEither, the newly completed task, performs a consumption operation on the result

RunAfterEither, after the execution of any task is completed, execute the Runnable operation

AnyOf, among multiple tasks, returns the CompletableFuture that was executed first.

5.1 example: two tasks are executed at the same time, printing the result of the first completed task package com.qcy.testCompleteableFuture; import java.util.concurrent.CompletableFuture; / * * @ author qcy * @ create 17:40:44 on 2020-09-07 * / public class Case7 {public static void main (String [] args) throws Exception {CompletableFuture completableFuture = CompletableFuture.supplyAsync (()-> {System.out.println ("Task 1 starts") Try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("Task 1 ends"); return 2;}) .task Either (CompletableFuture.supplyAsync ()-> {System.out.println ("Task 2 starts")) Try {Thread.sleep (2000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("Task 2 ends"); return 3;}), result-> System.out.println (result)) / / wait for CompletableFuture to return to prevent the main thread from exiting completableFuture.join ();}}

Output:

As you can see, after task 2 is over, the remaining code of task 1 is no longer executed

5.2 example: multiple tasks are executed at the same time, printing the result of the first completed task package com.qcy.testCompleteableFuture; import java.util.concurrent.CompletableFuture; / * * @ author qcy * @ create 17:40:44 on 2020-09-07 * / public class Case8 {public static void main (String [] args) throws Exception {CompletableFuture cf1 = CompletableFuture.supplyAsync (()-> {System.out.println ("Task 1 starts") Try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println (Task 1 ends); return 2;}) CompletableFuture cf2 = CompletableFuture.supplyAsync (()-> {System.out.println ("Task 2 starts"); try {Thread.sleep (2000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("Task 2 ends"); return 3 }); CompletableFuture cf3 = CompletableFuture.supplyAsync (()-> {System.out.println ("Task 3 starts"); try {Thread.sleep (4000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("Task 3 ends") Return 4;}); CompletableFuture firstCf = CompletableFuture.anyOf (cf1, cf2, cf3); System.out.println (firstCf.get ());}}

Output:

Thank you for your reading, the above is the content of "how to use CompletableFuture", after the study of this article, I believe you have a deeper understanding of how to use CompletableFuture, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report