package ThreadDemo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.var;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
public class CompletableFutureDemo<R,T> {
private static final ExecutorService THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(10, 10, 60L,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(100000));
public static void main(String[] args) {
CompletableFutureDemo completableFutureDemo=new CompletableFutureDemo();
List<Integer>list=new ArrayList<>();
list.add(999);
list.add(3);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
List future2 = completableFutureDemo.invokeAsyncForList(list,getF(list));
// CompletableFuture<String> future2 = new CompletableFuture();
Integer result = (Integer) future2.get(0);
System.out.println(result);
Integer result2 = (Integer) future2.get(1);
System.out.println(result);
Integer result3 = (Integer) future2.get(2);
System.out.println(result);
Integer result4 = (Integer) future2.get(3);
System.out.println(result);
}
public static Function<List<Integer>,List<Integer>> getF(List<Integer> integers){
return t->{
System.out.println(integers.size());
return Collections.singletonList(t.stream().reduce(Integer::sum).orElse(0));
};
};
public List<T> invokeAsyncForList(List<R> params, Function<List<R>, List<T>> function){
List<T> resultList = Lists.newArrayList();
//按指定长度 进行切分
List<List<R>> paramList = Lists.partition(params,2);
System.out.println(paramList.size());
try{
List<CompletableFuture<List<T>>> futureList = paramList
.stream()
.map(pa -> CompletableFuture.supplyAsync(() -> function.apply(pa) ,THREAD_POOL_EXECUTOR))
.collect(Collectors.toList());
List<List<T>> joinList = futureList.stream().map(CompletableFuture::join).collect(Collectors.toList());
joinList.stream().forEach(System.out::println);
joinList.stream().forEach(resultList::addAll);
}catch (Exception e) {
System.out.println(e.getMessage());
}
return resultList;
}
}
多线程学习一CompletableFutureDemo使用
最新推荐文章于 2022-12-23 19:35:49 发布