package com.canal.util;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
public class FutureTest {
private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(
10,// 核心线程池大小
20,// 最大线程池大小
10,// 线程最大空闲时间
TimeUnit.MILLISECONDS,// 时间单位
new ArrayBlockingQueue<>(1000),// 线程等待队列
Executors.defaultThreadFactory(),// 线程创建工厂
new ThreadPoolExecutor.AbortPolicy());// 拒绝策略
private AtomicInteger atomic = new AtomicInteger();
public static void main(String[] args) {
//CompletableFuture基本操作
futureTest();
//CompletableFuture多任务
FutureTest task = new FutureTest();
task.run().join().forEach(System.out::println);
executor.shutdown();
}
private static void futureTest() {
CompletableFuture<Result> futureA = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
log.info("执行线程A-----处理数据中----无操作--无返回--");
log.info("执行线程A-----结束----");
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Result("线程测试A", 1);
}).thenApplyAsync(s -> new Result("线程测试A", s.getAge() + 10));
CompletableFuture<Result> futureB = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
log.info("执行线程B-----处理数据中----无操作--无返回--");
log.info("执行线程B-----结束----");
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Result("线程测试B", 24);
});
CompletableFuture<ArrayList<Result>> futureC = futureA.thenCombineAsync(futureB, (rA, rB) -> {
ArrayList<Result> list = Lists.newArrayList();
Result rsA = (Result) rA;
Result rsB = (Result) rB;
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
rsA.setAge(rsA.getAge() + 1);
rsB.setAge(rsB.getAge() + 1);
log.info("执行线程保存处理结果-----resultA,age+1后为:{}----", rsA.toString());
log.info("执行线程保存处理结果-----resultB,age+1后为:{}----", rsB.toString());
list.add(rsA);
list.add(rsB);
log.info("执行线程保存处理结果-----结束----");
} catch (InterruptedException e) {
e.printStackTrace();
}
return list;
});
futureC.whenComplete((a, b) -> {
return;
});
log.info(futureC.join().toString());
}
@Data
private static class Result {
private String name;
private Integer age;
public Result(String name, Integer age) {
this.name = name;
this.age = age;
}
}
public CompletableFuture<List<String>> run() {
List<CompletableFuture<List<String>>> future = new ArrayList<>();
for (int i = 0; i < 10; i++) {
future.add(task());
}
return CompletableFuture.supplyAsync(() -> {
List<String> list = new ArrayList<>();
future.stream().parallel().forEach(task1 -> {
list.addAll(task1.join());
});
return list;
});
}
public CompletableFuture<List<String>> task() {
return CompletableFuture.supplyAsync(() -> {
// TODO:任务
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new ArrayList<String>() {{
add(atomic.getAndIncrement() + "->");
}};
}, executor);
}
}