zoukankan      html  css  js  c++  java
  • 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;
    	}
    
    }
    
  • 相关阅读:
    性能测试基础篇
    Jmeter参数化
    斐波那契
    Web安全 概述
    HTTP 协议详解
    echarts 响应式布局
    vue 结合mint-ui Message box的使用方法
    vue 中使用iconfont Unicode编码线上字体图标的流程
    手机端@media的屏幕适配
    @media响应式的屏幕适配
  • 原文地址:https://www.cnblogs.com/zhucww/p/11196272.html
Copyright © 2011-2022 走看看