编程语言
首页 > 编程语言> > java回调函数

java回调函数

作者:互联网

异步回调(理解成ajax)
对将来某个事件的结果进行建模

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class FutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(
                ()->{
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+
                            "【CompletableFuture.runAsync】");
                }

        );
        System.out.println("【执行main线程】");
        System.out.println("【获取回调函数结果】"+completableFuture.get());

        CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"CompletableFuture.supplyAsync");
            return 1024;
        });
        System.out.println("执行main线程");
        System.out.println(completableFuture1.whenComplete((t, u) -> {
            System.out.println("t = " + t);
            System.out.println("u = " + u);
        }).exceptionally((e) -> {
            System.out.println("e.getMessage() = " + e.getMessage());
            return -1;
        }).get());
    }
}

 

标签:java,函数,System,InterruptedException,CompletableFuture,println,回调,out
来源: https://www.cnblogs.com/jzbl/p/16395412.html