package com.lomonke;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.ArrayList;
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 Lvdoudou
* @date 2023/5/30 0030 21:54
* @description CompletableFuture 的真实案例使用
*/
public class CompletableDemo2 {
/**
1.需求说明
1.1同一款产品,同时搜索出同款产品在各大电商平台的售价;
1.2同一款产品,同时搜索出本产品在同一个电商平台下,各个入驻卖家售价是多少
2.输出返回:
出来结果希望是同款产品的在不同地方的价格清单列表,返回一个List<String>
《mysql》in jd price is 88.05
《mysql》in dangdang price is 86.11
《mysql》in taobao price is 90.43
3. 解决方案,比对同一个商品在各个平台上的价格,要求获得一个清单列表,
1 step by step,按部就班,查完京东查淘宝,查完淘宝查天猫
2 all in,万箭齐发,一口气多线程异步任务同时查询。
* */
public static List<String> stepByStep(List<BookShop> list, String bookName) {
return list.stream().map(x -> {
try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); }
return String.format(bookName + "在 %s店里售价为: %.2f", x.getShopName(), x.getPrice(bookName));
}).collect(Collectors.toList());
}
public static List<String> allIn(List<BookShop> list, String bookName) {
return list.stream().map(x -> {
return CompletableFuture.supplyAsync(()-> {
try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); }
return String.format(bookName + "在 %s店里售价为: %.2f", x.getShopName(), x.getPrice(bookName));
});
}).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList());
}
public static void main(String[] args) {
List<BookShop> shopList = new ArrayList<>();
shopList.add(new BookShop("京东"));
shopList.add(new BookShop("淘宝"));
shopList.add(new BookShop("拼多多"));
shopList.add(new BookShop("拼多多"));
shopList.add(new BookShop("拼多多"));
shopList.add(new BookShop("拼多多"));
long starTime = System.currentTimeMillis();
List<String> result = stepByStep(shopList, "mysql");
result.forEach(System.out::println);
long endTime = System.currentTimeMillis();
System.out.println("一共花费了"+ (endTime - starTime) + "毫秒");
long starTime2 = System.currentTimeMillis();
List<String> result2 = allIn(shopList, "mysql");
result2.forEach(System.out::println);
long endTime2 = System.currentTimeMillis();
System.out.println("一共花费了"+ (endTime2 - starTime2) + "毫秒");
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
class BookShop {
private String shopName;
public double getPrice(String bookName) {
return ThreadLocalRandom.current().nextDouble() * 2 + bookName.charAt(0);
}
}
结果