说明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基础

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。