首页 > 其他 > 详细

completableFuture

时间:2019-07-16 19:14:50      阅读:117      评论:0      收藏:0      [点我收藏+]

completableFuture jian简化java异步开发

package org.coffee.mala.test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;

import org.springframework.stereotype.Service;

@Service
public class BookAsyncService {

    public BookDetails getBookDetails(String bookId) throws InterruptedException, ExecutionException {

        Book book = getBook(bookId);
        CompletableFuture<ChuBanShe> chuBanShe = CompletableFuture.supplyAsync(new Supplier<ChuBanShe>() {

            @Override
            public ChuBanShe get() {

                return getChuBanShe(book.getChuBanSheId());
            }

        });
        CompletableFuture<GongYingShang> gongYingShang = CompletableFuture.supplyAsync(new Supplier<GongYingShang>() {

            @Override
            public GongYingShang get() {

                return getGongYingShang(book.getGongYingShangId());
            }

        });
        CompletableFuture<BookDetails> result = chuBanShe.thenCombine(gongYingShang, (chs, gys) -> {
            BookDetails bookDetails = new BookDetails();
            bookDetails.setBook(book);
            bookDetails.setChuBanShe(chs);
            bookDetails.setGongYingShang(gys);
            return bookDetails;
        });
        return result.get();
    }

    public Book getBook(String bookId) {

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Book book = new Book();
        book.setId(bookId);
        book.setName("shu ming");
        book.setChuBanSheId("chuBanSheId");
        book.setGongYingShangId("gongYingShangId");
        return book;
    }

    public ChuBanShe getChuBanShe(String chuBanSheId) {

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ChuBanShe chuBanShe = new ChuBanShe();
        chuBanShe.setId(chuBanSheId);
        chuBanShe.setName("chu ban she");
        return chuBanShe;
    }

    public GongYingShang getGongYingShang(String gongYingShangId) {

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        GongYingShang gongYingShang = new GongYingShang();
        gongYingShang.setId(gongYingShangId);
        gongYingShang.setName("gong ying shang");
        return gongYingShang;
    }

}

completableFuture

原文:https://www.cnblogs.com/zhucww/p/11196272.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!