completableFuture

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

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