Java高级-CompletableFuture并发编程利器
CompletableFuture核心Api
- 1.概述
- 2.Async
- 2.a) supplyAsync
- 2.b) runAsync
- 3.Then
- 3.a) thenApply()
- 3.b) thenApplyAsync()
1.概述
Future可以在并发编程中异步获取结果
CompletableFuture实现了Future接口,肯定也会有Future的功能,也相当于是Future的一个升级版。
同时还实现了CompletionStage接口,CompletionStage表示某一个步骤,可以编排某些并发编程任务的功能
2.Async
2.a) supplyAsync
异步执行任务,任务有返回值
supplyAsync实现了Supplier接口
@Test
public void testSupplyAsync() throws ExecutionException, InterruptedException {// 设置线程池ExecutorService executorService = Executors.newFixedThreadPool(10);// 建议自己设置一个线程池。若未指定,将使用默认的线程池,会造成整个应用都会使用同一个线程池,会不太好CompletableFuture<String> task = CompletableFuture.supplyAsync(() -> {System.out.println(Thread.currentThread().getName());return "hello";}, executorService);// get()获取结果System.out.println(task.get());
}
2.b) runAsync
异步执行任务,任务没有返回值
runAsync实现了Runnable接口
@Test
public void testRunAsync() throws ExecutionException, InterruptedException {// 设置线程池ExecutorService executorService = Executors.newFixedThreadPool(10);// 建议自己设置一个线程池。若未指定,将使用默认的线程池,会造成整个应用都会使用同一个线程池,会不太好CompletableFuture task = CompletableFuture.runAsync(() -> System.out.println(Thread.currentThread().getName()));// get()获取结果System.out.println(task.get());
}
3.Then
当前一个异步任务执行完,才能执行本任务
当前执行thenApply()方法的线程来负责执行本任务,比如main线程。但是如果前一个异步任务还没有执行完,那么main线程就不能执行本任务了,要等前一个任务执行完后才能执行本任务。
3.a) thenApply()
当要睡眠1秒时,由主线程执行taskB
当不需要睡眠时,由执行taskA的子线程执行taskB,main线程会直接往下运行
@Test
public void testThen() throws InterruptedException {// 设置线程池ExecutorService executorService = Executors.newFixedThreadPool(10);Supplier<String> taskA = () -> {System.out.println("1: " + Thread.currentThread().getName());return "TaskA";};Function<String, String> taskB = (s) -> {System.out.println("2: " + Thread.currentThread().getName());return s + "TaskA";};CompletableFuture<String> future = CompletableFuture.supplyAsync(taskA, executorService);Thread.sleep(1000);// taskB 在 taskA 任务后执行,future.thenApply(taskB);System.out.println(Thread.currentThread().getName() + ": Finish...");
}
3.b) thenApplyAsync()
用另外的线程去执行任务
可以指定线程池来运行任务,若未指定,将使用默认的线程池。
该方法不会使用main线程去执行taskB
@Test
public void testThen() throws InterruptedException {// 设置线程池ExecutorService executorService = Executors.newFixedThreadPool(10);Supplier<String> taskA = () -> {System.out.println("1: " + Thread.currentThread().getName());return "TaskA";};Function<String, String> taskB = (s) -> {System.out.println("2: " + Thread.currentThread().getName());return s + "TaskA";};CompletableFuture<String> future = CompletableFuture.supplyAsync(taskA, executorService);Thread.sleep(1000);// taskB 在 taskA 任务后执行,future.thenApplyAsync(taskB, executorService);System.out.println(Thread.currentThread().getName() + ": Finish...");
}