用并行任务有什么好处,先来看一张图
创建异步线程任务
根据runnable创建CompletableFuture任务(无返回值)
//使用内置线程ForkJoinPool.commonPool(),根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable)
//指定自定义线程,根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
demo1代码
/**
* <p>
* Description: TODO
* </p>
*
* @author songzixian
* @version v2.0.0
* @create 2022-08-20 22:17
* @see com.songzixian.demo.completablefuture
*/
public class Demo5 {
public static void main(String[] args) {
long time = System.currentTimeMillis();
Map<String,Object> map = new ConcurrentHashMap<>();
CompletableFuture.allOf(
CompletableFuture.runAsync(() -> {
ThreadTool.printTimeAndThread("业务1开始执行了");
ThreadTool.sleepMillis(200);
map.put("1","执行完成");
}),
CompletableFuture.runAsync(() -> {
ThreadTool.printTimeAndThread("业务2开始执行了");
ThreadTool.sleepMillis(200);
map.put("2","执行完成");
}),
CompletableFuture.runAsync(() -> {
ThreadTool.printTimeAndThread("业务3开始执行了");
ThreadTool.sleepMillis(200);
map.put("3","执行完成");
})
).join();
long ms = System.currentTimeMillis() - time;
System.out.println("办法总消耗时:" + ms + " ms");
System.out.println(map.toString());
}
}
控制台打印
根据supplier创建CompletableFuture任务(有返回值)
//使用内置线程ForkJoinPool.commonPool(),根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
//指定自定义线程,根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
demo2代码
/**
*
* @author songzixian
*/
public class Demo6 {
public static void main(String[] args) {
Map<String,Object> map = new ConcurrentHashMap<>();
CompletableFuture.allOf(
CompletableFuture.supplyAsync(() -> {
ThreadTool.printTimeAndThread("业务1开始执行");
ThreadTool.sleepMillis(200);
map.put("1","执行完成");
//返回执行结果
return "业务一结果";
//传入dist代表返货到上面的返回结果 ->"服务员制作好咖啡机了"
}),
CompletableFuture.supplyAsync(() -> {
ThreadTool.printTimeAndThread("业务2开始执行");
ThreadTool.sleepMillis(200);
map.put("2","执行完成");
//返回执行结果
return "业务二结果";
//传入dist代表返货到上面的返回结果 ->"服务员制作好咖啡机了"
}),
CompletableFuture.supplyAsync(() -> {
ThreadTool.printTimeAndThread("业务3开始执行");
ThreadTool.sleepMillis(200);
map.put("3","业务三结果");
//返回执行结果
return "服务员制作好了第一杯咖啡";
//传入dist代表返货到上面的返回结果 ->"服务员制作好咖啡机了"
})
).join();
System.out.println(map.toString());
}
}
控制台打印