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 Java Asynchronous programming

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

Share

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

This article mainly introduces "how to use Java asynchronous programming". In daily operation, I believe many people have doubts about how to use Java asynchronous programming. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use Java asynchronous programming"! Next, please follow the editor to study!

1. Create asynchronous thread task according to supplier create CompletableFuture task / / use built-in thread ForkJoinPool.commonPool (), build execution task public static CompletableFuture supplyAsync (Supplier supplier) / / specify custom thread according to supplier build execution task public static CompletableFuture supplyAsync (Supplier supplier, Executor executor) create CompletableFuture task according to runnable / / use built-in thread ForkJoinPool.commonPool (), execute task public static CompletableFuture runAsync (Runnable runnable) / / specify custom thread according to runnable build Execute the task public static CompletableFuture runAsync (Runnable runnable, Executor executor) according to runnable build

Use the example

ExecutorService executor = Executors.newSingleThreadExecutor (); CompletableFuture rFuture = CompletableFuture .runAsync (()-> System.out.println ("hello siting"), executor); / / use of supplyAsync CompletableFuture future = CompletableFuture. SupplyAsync (()-> {System.out.print ("hello"); return "siting";}, executor); / / blocking wait, future of runAsync has no return value, output nullSystem.out.println (rFuture.join ()) / / blocking wait String name = future.join (); System.out.println (name); executor.shutdown (); / / Thread pool needs to be closed-output result-hello sitingnullhello siting constant value is returned as CompletableFuture / / sometimes it is necessary to build a constant CompletableFuturepublic static CompletableFuture completedFuture (U value) 2, thread serial execution

Run action when the task is completed, do not care about the result of the previous task, and have no return value

Public CompletableFuture thenRun (Runnable action) public CompletableFuture thenRunAsync (Runnable action) public CompletableFuture thenRunAsync (Runnable action, Executor executor)

Use the example

CompletableFuture future = CompletableFuture .supplyAsync (()-> "hello siting", executor) .thenRunAsync (()-> System.out.println ("OK"), executor); executor.shutdown () -output result-run action when the OK task is completed, depending on the result of the previous task, and no return value public CompletableFuture thenAccept (Consumer other, Runnable action) public CompletableFuture runAfterBothAsync (CompletionStage other, Runnable action) public CompletableFuture runAfterBothAsync (CompletionStage other, Runnable action, Executor executor)

Use the example

/ / the first asynchronous task, constant task CompletableFuture first = CompletableFuture.completedFuture ("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor (); CompletableFuture future = CompletableFuture / / the second asynchronous task. SupplyAsync (()-> "hello siting", executor) / / ()-> System.out.println ("OK") is the third task. RunAfterBothAsync (first, ()-> System.out.println ("OK"), executor) Executor.shutdown ();-output result-OK two CompletableFuture [parallel] execution, and then execute action, depending on the results of the previous two tasks, no return value / / the first task completes and then runs other,fn to consume the results of two tasks, no return value public CompletableFuture thenAcceptBoth (CompletionStage other, Runnable action) public CompletableFuture runAfterEitherAsync (CompletionStage other, Runnable action) public CompletableFuture runAfterEitherAsync (CompletionStage other, Runnable action, Executor executor)

Use the example

/ / the first asynchronous task, dormant for 1 second, ensures late execution of CompletableFuture first = CompletableFuture.supplyAsync (()-> {try {Thread.sleep (1000);} catch (Exception e) {} System.out.println ("hello world"); return "hello world";}); ExecutorService executor = Executors.newSingleThreadExecutor () CompletableFuture future = CompletableFuture / / second asynchronous task. SupplyAsync (()-> {System.out.println ("hello siting"); return "hello siting";}, executor) / / ()-> System.out.println ("OK") is the third task. RunAfterEitherAsync (first, ()-> System.out.println ("OK"), executor) Executor.shutdown ();-output results-hello sitingOK the last task or other task completed, run action, depending on the result of the first task completed, no return value public CompletableFuture acceptEither (CompletionStage... Cfs) public static CompletableFuture anyOf (CompletableFuture... Cfs)

Use the example

CompletableFuture future = CompletableFuture .allOf (CompletableFuture.completedFuture ("A"), CompletableFuture.completedFuture ("B")); / / all tasks need to finish executing future.join (); CompletableFuture future2 = CompletableFuture .anyOf (CompletableFuture.completedFuture ("C"), CompletableFuture.completedFuture ("D")); / / one of the tasks can be future2.join (); 7. Cancel the execution of thread tasks / / mayInterruptIfRunning has no effect. If the task is not completed, it returns the exception public boolean cancel (boolean mayInterruptIfRunning) / / whether the task cancels public boolean isCancelled ()

Use the example

CompletableFuture future = CompletableFuture .supplyAsync (()-> {try {Thread.sleep (1000);} catch (Exception e) {} return "hello world";}) .thenApply (data-> 1); System.out.println ("before Task cancels:" + future.isCancelled ()) / / if the task is not completed, an exception is returned, and you need to process future.cancel (true) for the result using exceptionally,handle; System.out.println ("after the task is cancelled:" + future.isCancelled ()); future = future.exceptionally (e-> {e.printStackTrace (); return 0;}); System.out.println (future.join ()) -output result-before the task is cancelled: after the false task is cancelled: truejava.util.concurrent.CancellationException at java.util.concurrent.CompletableFuture.cancel (CompletableFuture.java:2276) at Test.main (Test.java:25) 08, the acquisition and completion of the task determines / / whether the task is completed or not. Public boolean isDone () / blocking waits to get the return value public T join () / / blocking waits to get the return value The difference is that get needs to return the checked exception public T get () / / wait for blocking for a period of time. And get the return value public T get (long timeout, TimeUnit unit) / / if it is not completed, the specified valuepublic T getNow (T valueIfAbsent) / / is not completed. Use value as the result of the task execution, and the task ends. If future.get is required to get public boolean complete (T value) / / not completed, it is an exception call and returns the exception result. The task ends public boolean completeExceptionally (Throwable ex) / / determines whether the task ends because of the public boolean isCompletedExceptionally () / / which determines whether the task ends because of the exception, and forcibly sets the return value to value, regardless of whether the previous task is completed or not; similar to completepublic void obtrudeValue (T value) / / forcibly throws an exception and returns the exception, regardless of whether the previous task is completed or not Similar to completeExceptionallypublic void obtrudeException (Throwable ex)

Use the example

CompletableFuture future = CompletableFuture. SupplyAsync (()-> {try {Thread.sleep (1000);} catch (Exception e) {} return "hello world";}) .thenApply (data-> 1); System.out.println (before Task completion: + future.isDone ()); future.complete (10); System.out.println (after Task completion: + future.join ()) -output results-before task completion: false task completed: 10 this is the end of the study on "how to use Java asynchronous programming", hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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