<> Asynchronous callback
Future The original intention of the design : Model the results at a certain time in the future
Code examples
package com.future; import java.util.concurrent.CompletableFuture; import java.
util.concurrent.ExecutionException; import java.util.concurrent.Future; import
java.util.concurrent.TimeUnit; /** * * Asynchronous call :Ajax * // Asynchronous execution * // Successful callback * // Failed callback * *
*/ public class Demo01 { public static void main(String[] args) throws
ExecutionException, InterruptedException { // Make a request Void yes void Packaging // With no return value
runAsync Asynchronous callback // CompletableFuture<Void> completableFuture =
CompletableFuture.runAsync(()->{ // try { // TimeUnit.SECONDS.sleep(2); // }
catch (InterruptedException e) { // e.printStackTrace(); // } //
System.out.println(Thread.currentThread().getName()+"runAsync"); // }); //
System.out.println("1111"); // completableFuture.get();// Get blocking execution results
// Asynchronous callback with return value ,Supplier Supply interface , No reference , There is a return value ! // ajax, Success and failure callbacks // Failure is an error message returned
CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(()
-> { System.out.println(Thread.currentThread().getName()+"supplyAsync=>Integer")
; int i =10/0; return 1024; }); System.out.println(completableFuture1.
whenComplete((t, u) -> { System.out.println("t=>" + t);// Normal return result System.out.
println("u=>" + u);// error message :java.util.concurrent.CompletionException }).
exceptionally((t) -> { System.out.println(t.getMessage()); return 233;
// You can get the wrong result }).get()); /** * General business return code * success Code 200 * error Code 404
500 */ } }
Output results :
ForkJoinPool.commonPool-worker-1supplyAsync=>Integer
t=>null
u=>java.util.concurrent.CompletionException: java.lang.ArithmeticException: /
by zero
java.lang.ArithmeticException: / by zero
233
Technology