Future和CompletableFuture的初步API的学习

Future和Callable结合的使用

	FutureTask<String> futureTask = new FutureTask(() -> {
		Thread.sleep(20000);
		return "1";
	});
	ExecutorService executorService = Executors.newFixedThreadPool(1);
	executorService.submit(futureTask);
	System.out.println(futureTask.get());
	executorService.shutdown();
1. 获取任务返回值

get() / get(long timeout, TimeUnit unit):

该方法会阻塞,直到任务结束返回值获取到才结束阻塞,

timeout: 超时时间,超过指定超时时间没有获取到任务返回值,抛出异常

unit: 超时时间单位

	FutureTask<String> futureTask = new FutureTask(() -> {
		// 模拟任务执行中
		for(;!Thread.currentThread().isInterrupted();){
			System.out.println("1");
		}
		return "1";
	});
	ExecutorService executorService = Executors.newFixedThreadPool(1);
	executorService.submit(futureTask);
	Thread.sleep(8000);
	System.out.println(futureTask.cancel(true) + "" + futureTask.isCancelled());
	executorService.shutdown();
2. 取消任务

cancel(boolean mayInterruptIfRunning):

mayInterruptIfRunning: 是否中断任务

在这里插入图片描述

true - 中断任务,从源码得知cancel是通过Thread.interrupt()中断程序,所以只能中断任务重join() , sleep(), wait()等方法的执行,如果想中断程序可以在任务执行代码中 加一个条件判断 !Thread.currentThread().isInterrupted() 实现一个任务取消

false - 如果任务开始了,则不中断任务,如果任务没开始则中断任务

CompletableFuture的使用

	CompletableFuture<String> objectCompletableFuture = CompletableFuture.supplyAsync(() -> {
		System.out.println(Thread.currentThread().getName());
		return "1-2-3";
	});
	System.out.println(objectCompletableFuture.get());

注意:【以下执行任务方法,如果没有没有指定,线程池默认使用 ForkJoinPool.commonPool()】

1. CompletableFuture runAsync(Runnable runnable)

没有返回值的任务实例

2. CompletableFuture supplyAsync(Supplier supplier)

有返回值得任务实例,函数式接口的supplier

3. T get()

获取任务返回值,没有则阻塞直到有返回值返回,与Future用法一致

注意:【以下执行任务方法,后缀以Async结尾的执行的任务是交由线程池去分配线程去执行,而不是以Async结尾的执行的任务交由上一个任务线程执行】

4.1. CompletableFuture whenComplete(BiConsumer<? super T, ? super Throwable> action)
4.2. CompletableFuture whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action)

之后执行的任务,接受参数是函数式接口consumer【接收: 返回结果,任务发生异常对象】

5.1. CompletableFuture thenAccept(Consumer<? super T> action)
5.2. CompletableFuture thenAcceptAsync(Consumer<? super T> action)

之后执行的任务,接受参数是函数式接口consumer【接收: 返回结果】

6.1. CompletableFuture thenApply(Function<? super T,? extends U> fn)
6.2. CompletableFuture thenApplyAsync(Function<? super T,? extends U> fn)

之后执行的任务,接受参数是函数式接口function【接收: 返回结果, 返回: 返回结果】

7.1. CompletableFuture handle(BiFunction<? super T, Throwable, ? extends U> fn)
7.2. CompletableFuture handleAsync(Function<? super T,? extends U> fn)

之后执行的任务,接受参数是函数式接口function【接收: 返回结果, 任务发生异常对象, 返回: 返回结果】

8.1. CompletableFuture thenRun(Runnable action)
8.2. CompletableFuture thenRunAsync(Runnable action)

之后执行的任务,接受参数是Runnable 无返回值

9.1. CompletableFuture thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action)
9.2. CompletableFuture thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action)

两个CompletableFuture任务完成后,接受参数是 另一个CompletableFuture任务, consumer函数式接口【接收: 返回结果】

10.1. CompletableFuture thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
10.2. CompletableFuture thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)

两个CompletableFuture任务完成后,接受参数是 另一个CompletableFuture任务, function函数式接口【接收: 返回结果, 返回: 返回结果】

11.1. CompletableFuture runAfterBoth(CompletionStage<?> other,Runnable action)
11.2. CompletableFuture runAfterBothAsync(CompletionStage<?> other,Runnable action)

两个CompletableFuture任务完成后,接受参数是 另一个CompletableFuture任务, Runnable接口 无返回值

12.1. CompletableFuture applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn)
12.2. CompletableFuture applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn)

哪个线程先返回就使用谁的返回结果进入该方法,接受参数是 另一个CompletableFuture任务, function函数式接口【接收: 返回结果, 返回: 返回结果】

13.1. CompletableFuture acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
13.2.CompletableFuture acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action)

哪个线程先返回就使用谁的返回结果进入该方法,接受参数是 另一个CompletableFuture任务, consumer函数式接口【接收: 返回结果】

14.1. CompletableFuture runAfterEither(CompletionStage<?> other, Runnable action)
14.2. CompletableFuture runAfterEitherAsync(CompletionStage<?> other, Runnable action)

哪个线程先返回就使用谁的返回结果进入该方法,接受参数是 另一个CompletableFuture任务, Runnable接口 无返回值

15. static CompletableFuture allOf(CompletableFuture<?>… cfs)

等待所有线程结束再执行对应的任务

	CompletableFuture<String> stringCompletableFuture1 = CompletableFuture.supplyAsync(() -> {
		System.out.println("123");
		return "123";
	});
	CompletableFuture<String> stringCompletableFuture2 = CompletableFuture.supplyAsync(() -> {
		System.out.println("456");
		return "456";
	});
	CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(stringCompletableFuture1, stringCompletableFuture2);
	CompletableFuture<Integer> integerCompletableFuture = voidCompletableFuture.thenRunAsync(() -> {
		try {
			System.out.println(stringCompletableFuture1.get());
			System.out.println(stringCompletableFuture2.get());
			int sum = new Integer(stringCompletableFuture1.get()) + new Integer(stringCompletableFuture2.get());
			System.out.println(sum);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	});
	System.out.println(integerCompletableFuture.get());
	
16. static CompletableFuture anyOf(CompletableFuture<?>… cfs)

有任一一个任务完成返回结果就获取到该任务的结果,并执行相对应的任务

	CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(stringCompletableFuture1, stringCompletableFuture2);
	CompletableFuture<String> stringCompletableFuture = objectCompletableFuture.thenApplyAsync((v) -> {
		System.out.println("v = " + v);
		return "123";
	});
	System.out.println(stringCompletableFuture.get());
17.1. CompletableFuture thenCompose(Function<? super T, ? extends CompletionStage> fn)
17.2. CompletableFuture thenComposeAsync(Function<? super T, ? extends CompletionStage> fn)

将两个线程串行连接起来,只有第一个线程返回结果时,才会将返回值作为参数传给第二个线程执行。

18. CompletableFuture exceptionally(Function<Throwable, ? extends T> fn)

执行任务出现了错误就执行该任务

19. T getNow(T valueIfAbsent)

现在获取任务结果,如果任务在此刻完成返回结果则得到任务返回结果,否则获得valueIfAbsent

20.1. boolean complete(T value)
20.2. boolean completeNull()

20.1. 如果任务未完成,返回设置返回结果,并把任务标记完成
20.2. 如果任务未完成,返回null,并把任务标记完成

21. boolean completeExceptionally(Throwable ex)

如果任务未完成,抛出指定异常,并把任务标记完成

22. CompletableFuture completedFuture(U value)

创建一个预定义结果的CompletableFuture对象






一键查询淘宝/拼多多内部优惠券,每日大额外卖红包,购物省钱的宝藏工具
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值