CompletableFuture-电商比价大厂案例

package com.nanjing.gulimall.zhouyimo.test;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zhou
 */
public class CompletableFutureMallDemo2 {
    static List list = Arrays.asList(new NetMall("jd"), new NetMall("taobao"), new NetMall("dangdang"));

    public static List getPrice(List list, String productName) {
        //返回这种格式《Mysql》 in jd price is 88.05
        return list.stream()
                .map(netMall -> String.format("《" + productName + "》" + "in %s price is %.2f", netMall.getNetMallName(), netMall.calcPrice(productName)))
                .collect(Collectors.toList());
    }

    /**
     * 把list里面的内容映射给CompletableFuture()
     * @param list
     * @param productName
     * @return
     */
    public static List getPriceByCompletableFuture(List list, String productName) {
        return list.stream().map(netMall ->
                        CompletableFuture.supplyAsync(() ->
                                String.format("《" + productName + "》" + "in %s price is %.2f", netMall.getNetMallName(), netMall.calcPrice(productName)))) //Stream>
                .collect(Collectors.toList()) //List>
                .stream()//Stream
                .map(s -> s.join()).collect(Collectors.toList()); //List
    }

    public static void main(String[] args) {
        long StartTime = System.currentTimeMillis();
        List strings = getPrice(list, "mysql");
        for (String s : strings) {
            System.out.println(s);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("------costTime: " + (endTime - StartTime) + " 毫秒");
        /*《mysql》in jd price is 109.12
        《mysql》in taobao price is 110.04
        《mysql》in dangdang price is 109.15
        ------costTime: 3070 毫秒*/


        long StartTime2 = System.currentTimeMillis();
        List stringList = getPriceByCompletableFuture(list, "mysql");
        for (String s : stringList) {
            System.out.println(s);
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("------costTime" + (endTime2 - StartTime2) + " 毫秒");
        /*《mysql》in jd price is 109.12
        《mysql》in taobao price is 110.37
        《mysql》in dangdang price is 110.3
         ------costTime1015 毫秒*/
    }
}

@AllArgsConstructor
@NoArgsConstructor
@Data
class NetMall {

    private String netMallName;

    public double calcPrice(String productName) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //模拟书的价格
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }
}

 

 

你可能感兴趣的:(JUC并发编程与源码分析,java)