说明1、JDK 8中引入了 CompletableFuture 类,实现了Future和CompletionStage接口.为异步编程提供了一些列方法,如supplyAsync、runAsync和thenApplyAsync等。2、功能是可以让两个或者多个进行运算来产生结果。实例

/***@authormghio*@since2021-08-01*/publicclassCompletableFutureDemo{publicstaticCompletableFuture<String>doOneThing(){returnCompletableFuture.supplyAsync(()->{try{Thread.sleep(2000);catch(InterruptedExceptione){e.printStackTrace();return"doOneThing";);publicstaticCompletableFuture<String>doOtherThing(Stringparameter){returnCompletableFuture.supplyAsync(()->{try{Thread.sleep(2000);catch(InterruptedExceptione){e.printStackTrace();returnparameter+""+"doOtherThing";);publicstaticvoidmain(String[]args)throwsExecutionException,InterruptedException{StopWatchstopWatch=newStopWatch("CompletableFutureDemo");stopWatch.start();//异步执行版本testCompletableFuture();stopWatch.stop();System.out.println(stopWatch);privatestaticvoidtestCompletableFuture()throwsInterruptedException,ExecutionException{//先执行doOneThing任务,后执行doOtherThing任务CompletableFuture<String>resultFuture=doOneThing().thenCompose(CompletableFutureDemo::doOtherThing);//获取任务结果StringdoOneThingResult=resultFuture.get();//获取执行结果System.out.println("DoOneThingandDoOtherThingexecutefinished.result="+doOneThingResult);

以上就是java中CompletableFuture方式的介绍,希望对大家有所帮助。更多Java学习指路:Java基础

发表回复