completableFuture

独自空忆成欢 提交于 2019-11-26 21:14:13

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;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!