1、线程池的创建
ThreadPoolExecutor executor = new ThreadPoolExecutor(5,//核心线程数,一直存在,都在执行的情况下临时存放到阻塞队列,等待核心线程执行
200,//最大可同时执行的线程数量,阻塞队列满了,调用这些线程执行任务
10,//空闲线程存活时间,也就是阻塞队列满了启动的这些线程任务执行结束之后存活的时间
TimeUnit.SECONDS,//时间单位
new LinkedBlockingDeque<>(100000),//提交到线程池的任务过多,核心线程执行不过来的任务临时存放到这个队列中等待核心线程执行
Executors.defaultThreadFactory(),//线程池创建的工厂,可以自定义线程池
new ThreadPoolExecutor.AbortPolicy()//拒绝策略,当整个线程池到达最大线程数后,对提交的任务进行不同的处理的策略,可以丢弃,可以直接执行,可以排在最前面把最后一个丢掉,或者把最后一个丢掉取代它,或者抛异常
);
2、异步编排completableFuture
1、CompletableFuture.supplyAsync(线程任务,线程池).handle((线程任务返回结果,捕捉的异常)->{});
//推荐使用这种方式处理返回结果和异常
CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 0;
System.out.println("结果:" + i);
return i;
}, executor).handle((res,thr)->{
if (res != null){
return res+666;
}
if (thr != null){
return 0;
}
return 0;
});
System.out.println("任务执行完返回的结果:"+integerCompletableFuture.get());
2、异步线程串行化 thenRunAsync thenAccept thenApplyAsync
//异步线程串行化
//1 thenRunAsync 不能获取上一步的结果,仅仅是等上一个任务执行结束之后执行第二个任务,并且整个任务执行结束之后无法获取返回结果
* CompletableFuture<Void> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 1;
System.out.println("结果:" + i);
return i;
}, executor).thenRunAsync(()->{
System.out.println("任务2执行");
},executor);
//2 thenAccept 可接收上一步的结果,但没有返回值
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 1;
System.out.println("结果:" + i);
return i;
}, executor).thenAccept((res) -> {//可接收上一步的结果,但没有返回值
System.out.println("任务一的结果:" + res);
});
//3 thenApplyAsync 可接收上一步的结果,也有返回值
CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 1;
System.out.println("结果:" + i);
return i;
}, executor).thenApplyAsync((res) -> {
System.out.println("任务一的结果:" + res);
return 20;
}, executor);
System.out.println("任务链执行完返回的结果:"+integerCompletableFuture.get());
3 任务组合
/***
* 多任务组合
* 1 allOf 等待所有的任务执行结束再往下走
* 2 anyOf 一个任务执行完成即可结束阻塞
*/
CompletableFuture<String> img = CompletableFuture.supplyAsync(() -> {
System.out.println("查询商品的图片信息");
return "hello.jpg";
},executor);
CompletableFuture<String> attr = CompletableFuture.supplyAsync(() -> {
System.out.println("查询商品的属性信息");
return "12+128";
},executor);
CompletableFuture<String> info = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
System.out.println("查询商品的介绍");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "真我";
},executor);
CompletableFuture<Object> future = CompletableFuture.anyOf(img, attr, info);
future.get();//阻塞,等待所有线程任务执行结束
System.out.println("任务编排执行结果"+future.get());