文章目录
一、线程回顾
public static final ExecutorService service = Executors.newFixedThreadPool(10);
/**
* 1.继承Thread
* Thread01 thread = new Thread01();
* thread.start();
*
* 2.实现Runnable接口
* Runnable01 runnable = new Runnable01();
* new Thread(runnable).start();
*
* 3.实现Callable接口+FutureTask(可以拿到返回值结果,可以处理异常)
* FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
* new Thread(futureTask).start();
* // 阻塞等待整个线程执行完成,获取返回结果
* Integer i = futureTask.get();
*
* 4.线程池
* 给线程池直接提交任务。
*
* 在业务代码中,1,2,3启动线程的方式都不用【将所有多线程异步任务都交给线程池执行】
*
* 区别:
* 1,2不能得到返回值,3可以获取返回值
* 1,2,3都不能控制资源,4可以控制资源,性能稳定
*
* ThreadPoolExecutor(int corePoolSize,
* int maximumPoolSize,
* long keepAliveTime,
* TimeUnit unit,
* BlockingQueue<Runnable> workQueue,
* ThreadFactory threadFactory,
* RejectedExecutionHandler handler)
*
* corePoolSize:核心线程数[一直存在除非allowCoreThreadTimeOut],
* 线程池,创建好以后就准备就绪的线程数量,就等待来接受异步任务来执行
*
* maximumPoolSize:最大线程数量;控制资源
*
* keepAliveTime:存活时间,如果当前线程数量大于core数量,释放空闲线程(maximumPoolSize-corePoolSize),
* 只要空闲线程空闲时间大于keepAliveTime就会被释放
*
* unit:keepAliveTime的时间单位
*
* workQueue:阻塞队列,如果任务有很多,就会将目前多的任务放在队列里,
* 只要有线程空闲,就会去队列里取出新的任务继续执行
*
* new LinkedBlockingQueue<Runnable>()
* this(Integer.MAX_VALUE); 默认是Integer的最大值,会引发内存不足问题
*
* threadFactory:线程的创建工厂
*
* handler:如果队列满了,就会按照我们指定的拒绝策略拒绝执行任务
*
*
* 工作顺序:
* 1. 线程池创建,准备好core数量的核心线程,准备接受任务
* 1.1. core满了,就将再进来的任务放入阻塞队列中,空闲的core就会自己去阻塞队列中获取任务执行
* 1.2. 阻塞队列满了,就直接开新线程执行,最大只能开到max的数量
* 1.3. 如果线程数开到了max的数量,还有新任务进来,就会使用reject指定的拒绝策略进行处理
* 1.4. max都执行完毕了,有很多空闲,在指定的时间keepAliveTime以后释放max-core这些线程
*
*
*
* 一个线程池:core7、max20、queue50,假如有100并发的进来怎么分配的?
*
* 先有7个能直接得到执行,接下来50个进入队列排队,再多开13个继续执行,现在70个被安排上了,剩下的30个默认拒绝策略。
* 如果不想任务被拒绝抛弃,则可以指定拒绝策略为:CallerRunsPolicy
*
*
*
*/
public static void main(String[] args) {
new Thread01().start();
new Thread(new Runnable01()).start();
FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
new Thread(futureTask).start();
service.execute(new Runnable01());
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
//Executors.newCachedThreadPool() core是0,所有都可回收
//Executors.newFixedThreadPool() 固定大小,core=max,都不可回收
//Executors.newScheduledThreadPool() 定时任务的线程池
//Executors.newSingleThreadExecutor() 单线程线程池,后台从队列里获取任务,挨个执行
}
public static class Thread01 extends Thread {
@Override
public void run() {
System.out.println("我是Thread01");
}
}
public static class Runnable01 implements Runnable {
@Override
public void run() {
System.out.println("我是Runnable01");
}
}
public static class Callable01 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("我是Callable01");
return 1;
}
}
1.初始化线程的4种方式
-
继承Thread
-
实现Runnnable接口
-
实现Callable+FutureTask(可以拿到返回结果,可以处理异常)
-
线程池
方式1和方式二:主进程无法获取线程的运算结果,不适合当前场景
方式3可以获取现成的运算结果,但是不利于控制服务器中的线程资源,可能导致服务器资源耗尽。
方式4通过如下两种方式初始化线程池
Executors.newFixedThreadPool(3)
// 或者
new ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
通过线程池性能稳定,也可以获取执行结果,并能捕获异常。但是,在业务复杂的情况下,一个异步调用可以会依赖另一个异步调用的执行结果。
2.线程池的七大参数
/**
*
* ThreadPoolExecutor(int corePoolSize,
* int maximumPoolSize,
* long keepAliveTime,
* TimeUnit unit,
* BlockingQueue<Runnable> workQueue,
* ThreadFactory threadFactory,
* RejectedExecutionHandler handler)
*
* corePoolSize:核心线程数[一直存在除非allowCoreThreadTimeOut],
* 线程池,创建好以后就准备就绪的线程数量,就等待来接受异步任务来执行
*
* maximumPoolSize:最大线程数量;控制资源
*
* keepAliveTime:存活时间,如果当前线程数量大于core数量,释放空闲线程(maximumPoolSize-corePoolSize),
* 只要空闲线程空闲时间大于keepAliveTime就会被释放
*
* unit:keepAliveTime的时间单位
*
* workQueue:阻塞队列,如果任务有很多,就会将目前多的任务放在队列里,
* 只要有线程空闲,就会去队列里取出新的任务继续执行
*
* threadFactory:线程的创建工厂
*
* handler:如果队列满了,就会按照我们指定的拒绝策略拒绝执行任务
*/
运行流程
-
线程池创建,准备好core数量的核心线程,准备接受任务
-
新的任务进来,用core准备好的空闲线程执行
2.1. core满了,就将再进来的任务放入阻塞队列中,空闲的core就会自己去阻塞队列中获取任务执行
2.2. 阻塞队列满了,就直接开新线程执行,最大只能开到max的数量 2.3. max数量的线程都执行完毕了,max-core数量的线程会在keepAliveTime指定的时间后自动销毁,最终保持到core大小 2.4. 如果线程数开到了max的数量,还有新任务进来,就会使用reject指定的拒绝策略进行处理
-
所有的线程创建都是由指定的factory创建的
面试问题
一个线程池:core7、max20、queue50,假如有100并发的进来怎么分配的?
先有7个能直接得到执行,接下来50个进入队列排队,再多开13个继续执行,现在70个被安排上了,剩下的30个默认拒绝策略。
3.常见的四种线程池
1.newCachedThreadPool
创建一个可缓存的线程池,如果线程长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
2.newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
3.newScheduledThreadPool
创建一个定长线程池,支持定时及周期性执行任务
4.newSingleThreadExecutor
创建一个单线程化的线程池,他只会用唯一的工作线程来执行任务,保证所有任务
4.开发中为什么使用线程池
-
降低资源的消耗
通过重复利用已经创建好的线程降低线程的创建和销毁带来的损耗
-
提高响应速率
因为线程池中的线程数没有超过线程池的最大上限时,有的线程处于等待分配任务的状态,当任务来时无需创建新的线程就能执行
-
提高线程的可管理性
线程池会根据当前系统特点对池内的线程进行优化处理,减少创建和销毁线程带来的系统开销,无限的创建和销毁线程不仅消耗系统资源,还降低系统的稳定性,使用线程池进行统一分配
二、CompletableFuture异步编排
public static ExecutorService executor = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture.runAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}, executor);
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executor);
Integer result1 = future1.get();
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executor)
.whenComplete((res, exception) -> System.out.println("异步任务成功完成了。。。结果是:" + res + ", 异常是:" + exception));
CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executor).whenComplete((res, exception) -> {
// 虽然能得到异常信息,但是没法修改返回数据
System.out.println("异步任务成功完成了...结果是:" + res + "; 异常时:" + exception);
}).exceptionally(throwable -> {
// 可以感知异常, 同时返回默认值
return 10;
});
Integer result3 = future3.get();
System.out.println("result: " + result3);
// 方法执行完成后的处理
CompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 0;
System.out.println("运行结果:" + i);
return i;
}, executor).handle((res, throwable) -> {
System.out.println("异步任务成功完成了。。。结果是:" + res + ", 异常是:" + throwable);
if (res != null) {
return res * 2;
}
if (throwable != null) {
return 0;
}
return 0;
});
/**
* 线程串行化
* 1. thenRun:不能获取到上一步的执行结果
* thenRunAsync(() -> {
* System.out.println("任务2启动了...")
* }, executor)
*
* 2.thenAcceptAsync:能接受上一步的结果,但是无返回值
*
* 3.thenApplyAsync:能接受上一步的结果,有返回值
*/
CompletableFuture<String> future5 = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("运行结果:" + i);
return i;
}, executor).thenApplyAsync(res -> {
System.out.println("任务2启动了... " + res);
return "hello " + res;
}, executor);
System.out.println("future5: " + future5.get());
/**
* 两个都要完成
*/
CompletableFuture<Integer> future001 = CompletableFuture.supplyAsync(() -> {
System.out.println("future001线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("future001结束");
return i;
}, executor);
CompletableFuture<String> future002 = CompletableFuture.supplyAsync(() -> {
System.out.println("future002线程:" + Thread.currentThread().getId());
System.out.println("future002结束");
return "Hello";
}, executor);
future001.runAfterBothAsync(future002, () -> System.out.println("任务3开始...."), executor);
// void accept(T t, U u)
future001.thenAcceptBothAsync(future002, (f1, f2) -> System.out.println("任务3开始...之前的结果:" + f1 + "-->" + f2), executor);
// R apply(T t, U u)
CompletableFuture<String> combineFuture = future001
.thenCombineAsync(future002, (f1, f2) -> f1 + ": " + f2 + " -> haha", executor);
System.out.println("combineFuture: " + combineFuture.get());
/**
* 两个任务,只要有一个完成,我们就执行任务3
* runAfterEitherAsync:不感知结果,自己业务返回值
* acceptEitherAsync:感知结果,自己没有返回值
* applyToEitherAsync:感知结果,自己有返回值
*
*/
CompletableFuture<Object> future011 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future011线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("future011结束");
return i;
}, executor);
CompletableFuture<Object> future012 = CompletableFuture.supplyAsync(() -> {
System.out.println("future012线程:" + Thread.currentThread().getId());
System.out.println("future012结束");
return "Hello";
}, executor);
future011.runAfterEitherAsync(future012, () -> System.out.println("任务3开始...."),executor);
// void accept(T t);
future011.acceptEitherAsync(future012, res -> System.out.println("res: " + res), executor);
// R apply(T t);
CompletableFuture<String> applyToEitherAsync = future011
.applyToEitherAsync(future012, res -> res + "hahah", executor);
System.out.println( "applyToEitherAsync: "+applyToEitherAsync.get());
CompletableFuture<Object> futureImg = CompletableFuture.supplyAsync(() -> {
System.out.println("查询商品的图片信息");
return "Hello.jpg";
}, executor);
CompletableFuture<Object> futureAttr = CompletableFuture.supplyAsync(() -> {
System.out.println("查询商品的属性");
return "黑色+256G";
}, executor);
CompletableFuture<Object> futureDesc = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("查询商品介绍");
return "华为";
}, executor);
CompletableFuture<Void> allOf = CompletableFuture.allOf(futureImg, futureAttr, futureDesc);
allOf.get();
System.out.println("img: " + futureImg.get() + ", attr: " + futureAttr.get() + ", desc: " + futureDesc.get());
CompletableFuture<Object> anyOf = CompletableFuture.anyOf(futureImg, futureAttr, futureDesc);
System.out.println("anyOf: "+ anyOf.get());
}
业务场景:
查询商品详情页的逻辑比较复杂,有些数据还需要远程调用。必然需要花费更多的时间。
// 1. 获取sku的基本信息 0.5s
// 2. 获取sku的图片信息 0.5s
// 3. 获取sku的促销信息 1.0s
// 4. 获取spu的所有销售属性 1.0s
// 5. 获取规格参数组及组下的规格参数 1.5s
// 6. spu详情 1.0s
加入商品详情页的每个查询,需要如下标注的时间才能完成
那么,用户需要6.5s才能看到商品详情页的内容,很显然是不能接受的。
如果有多个线程同时完成这6步操作,也许只需要1.5s即可完成响应
Future是Java5添加的类,用来描述一个异步计算的结果。你可以使用’isDone‘方法检查当前Future是否执行完成
1.创建异步对象
CompletableFuture提供了四个静态方法来创建一个异步操作
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable,
Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
Executor executor)
1.runXXX都是没有返回结果的,supplyXXX都是可以获取返回结果的
2.可以传入自定义的线程池,否则就用默认的线程池
2.计算完成时回调方法
public CompletableFuture<T> whenComplete(
BiConsumer<? super T, ? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(
BiConsumer<? super T, ? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(
BiConsumer<? super T, ? super Throwable> action, Executor executor)
public CompletableFuture<T> exceptionally(
Function<Throwable, ? extends T> fn)
whenComplete可以处理正常和异常的计算结果,exceptionally处理异常情况
whenComplete和whenCompleteAsync的区别:
whenComplete:是执行当前任务的线程继续执行whenComplete的任务
whenCompleteAsync:是执行把whenCompleteAsync这个任务继续提交给线程池来进行执行
方法不以Async结尾,意味着Action使用相同的线程来执行,而Async可能会使用其他线程执行(如果是使用相同的线程池,也可能会被同一个线程选中执行)
3.handle方法
public <U> CompletableFuture<U> handle(
BiFunction<? super T, Throwable, ? extends U> fn)
public <U> CompletableFuture<U> handleAsync(
BiFunction<? super T, Throwable, ? extends U> fn)
public <U> CompletableFuture<U> handleAsync(
BiFunction<? super T, Throwable, ? extends U> fn, Executor executor)
和complete一样,可对结果做最后的处理(可处理异常),可改变返回值
4.线程串行化方法
public <U> CompletableFuture<U> thenApply(
Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(
Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(
Function<? super T,? extends U> fn, Executor executor)
public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
Executor executor)
public CompletableFuture<Void> thenRun(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action,
Executor executor)
thenApply方法:当一个线程依赖另一个线程时,获取上一个任务返回的结果,并返回当前任务的返回值
thenApply方法:消费处理结果。接受任务的处理结果,并消费处理,无返回结果
thenRun方法:只要上面的任务执行完成,就开始执行thenRun,只是处理完任务后,执行thenRun的后续操作
带有Async默认是异步执行的,同之前。
以上都要前置任务成功完成。
5.两任务组合-都要完成
public <U,V> CompletableFuture<V> thenCombine(
CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn)
public <U,V> CompletableFuture<V> thenCombineAsync(
CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn)
public <U,V> CompletableFuture<V> thenCombineAsync(
CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn, Executor executor)
public <U> CompletableFuture<Void> thenAcceptBoth(
CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action)
public <U> CompletableFuture<Void> thenAcceptBothAsync(
CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action)
public <U> CompletableFuture<Void> thenAcceptBothAsync(
CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action, Executor executor)
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
Runnable action)
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
Runnable action)
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
Runnable action,
Executor executor)
两个任务必须都完成,触发该任务。
thenCombine:组合两个future,获取两个future的返回结果,并返回当前任务的返回值。
thenAcceptBoth:组合两个future,获取两个future任务的返回结果,只需要两个future处理完任务后,处理该任务。
runAfterBoth:组合两个future,不需要获取future的结果,只需两个future处理完任务后,处理该任务。
6.两任务组合,一个完成
public <U> CompletableFuture<U> applyToEither(
CompletionStage<? extends T> other, Function<? super T, U> fn)
public <U> CompletableFuture<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn)
public <U> CompletableFuture<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn,
Executor executor)
public CompletableFuture<Void> acceptEither(
CompletionStage<? extends T> other, Consumer<? super T> action)
public CompletableFuture<Void> acceptEitherAsync(
CompletionStage<? extends T> other, Consumer<? super T> action)
public CompletableFuture<Void> acceptEitherAsync(
CompletionStage<? extends T> other, Consumer<? super T> action,
Executor executor)
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,
Runnable action)
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
Runnable action)
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
Runnable action,
Executor executor)
当两个任务中,任意一个future任务完成的时候,执行任务
applyToEither:两个任务有一个执行完成,获取他的返回值,处理任务并有新的返回值。
acceptEither:两个任务有一个执行完成,获取他的返回值,处理任务,没有新的返回值。
runafterEither:两个任务有一个执行完成,不需要获取future的结果,处理任务,也没有返回值
7.多任务组合
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
allOf:等待所有任务完成
anyOf:只要有一个任务完成