Java8并发新特性CompletableFuture

目录
  • 1.CompletableFuture是什么?
  • 2.CompletableFuture的方法使用说明
    • 2.1 CompletableFuture类提供几个静态方法来进行异步操作
    • 2.2 获取异步任务执行结果的方法 get()/join()
  • 3.CompletionStage的方法使用说明
    • 3.1 纯消费类型
    • 3.2 有返回值类型
    • 3.3 不消费也不返回类型
    • 3.4 组合类型
    • 3.5 任务事件类型
  • 4.CompletionStage异常处理方法
  • 5.方法类型总结

1.CompletableFuture是什么?

各位小伙伴是否有一种感觉,整天大量时间沉迷于业务开发的同时,缺少对于一些技术更新的关注,忽略掉了很多实用又简单的方法,以往我们做异步任务的时候都习惯于使用Callable或者Runnable接口去实现,今天我们就来聊聊与之不同的CompletableFuture类。

CompletableFuture针对Future接口做了改进,相比Callable/Runnable接口它支持多任务进行链式调用、组合、多任务并发处理。很多时候我们在设计过程中会想在一个异步任务执行完成后,直接获取它的结果传递给下一个任务继续执行后续的流程,这时候CompletableFuture的作用就来了。

CompletableFuture类关系图:

从以下类图可以看到,CompletableFuture实现了Future和CompletionStage两个接口,Future提供了获取任务执行结果和任务执行状态的功能。 CompletionStage表示一个任务的执行阶段,提供了诸多方法支持了多任务的聚合功能。

2.CompletableFuture的方法使用说明

2.1 CompletableFuture类提供几个静态方法来进行异步操作

supplyAsync与runAsync主要用于构建异步事件。

supplyAsync带有返回值的异步任务,支持在默认线程池ForkJoinPool.commonPool()中完成异步任务,也可以使用自定义线程池执行异步任务,结果返回一个新的CompletableFuture,返回结果类型U。最终的任务执行结果可通过返回CompletableFuture对象的 get()/join() 方法获取返回值。

// 使用默认线程池
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {...}
// 使用自定义线程池Executor
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) {...}

// ====================================demo华丽分割线============================================
CompletableFuture<String> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
    log.info("executing supplyAsync task ...");
    return "this is supplyAsync";
});
// 进入阻塞获取异步任务结果
log.info(supplyAsyncFuture.get());  // 输出结果:this is supplyAsync

runAsync不带返回值的异步任务,支持在默认线程池ForkJoinPool.commonPool()中完成异步任务,也可以使用自定义线程池执行异步任务,结果返回一个新的CompletableFuture,返回结果类型为Void,也就是无返回值。

public static CompletableFuture<Void> runAsync(Runnable runnable) {...}
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) {...}

// ====================================demo华丽分割线============================================
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
    log.info("executing runAsync task ...");
});
runAsyncFuture.get();

allOf:多个CompletableFuture任务并发执行,所有CompletableFuture任务完成时,返回一个新的CompletableFuture对象,其返回值为Void,也就是无返回值。

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {...}

// ====================================demo华丽分割线============================================
// allOf,可传递返回值不同类型的future,最终结果按自己设计预期处理即可
CompletableFuture<String> cf11 = CompletableFuture.supplyAsync(() -> {
    log.info("executing supplyAsync task cf11 ...");
    return "this is supplyAsync";
});
CompletableFuture<String> cf12 = CompletableFuture.supplyAsync(() -> {
    log.info("executing supplyAsync task cf12 ...");
    return "this is supplyAsync";
});
CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(cf11, cf12);
allOfFuture.get();

anyOf:多个CompletableFuture任务并发执行,只要有一个CompletableFuture任务完成时,就会返回一个新的CompletableFuture对象,并返回该CompletableFuture执行完成任务的返回值。

public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {...}

// ====================================demo华丽分割线============================================
CompletableFuture<String> cf21 = CompletableFuture.supplyAsync(() -> {
    log.info("executing supplyAsync task cf21 ...");
    return "this is supplyAsync cf21";
});
CompletableFuture<String> cf22 = CompletableFuture.supplyAsync(() -> {
    log.info("executing supplyAsync task cf22 ...");
    return "this is supplyAsync cf22";
});
CompletableFuture<Object> anyOfFuture = CompletableFuture.anyOf(cf21, cf22);
log.info("{}", anyOfFuture.get());  // 输出结果:this is supplyAsync cf21或cf22

2.2 获取异步任务执行结果的方法 get()/join()

join()和get()方法都是CompletableFuture对象基于阻塞的方式来获取异步任务执行结果。

  • get方法会抛出显示异常必须捕获处理,任务允许被中断抛出InterruptedException异常,通过带有超时时间的阻塞方式获取异步任务执行结果,超时等待无结果则中断任务抛出TimeoutException异常。
  • join方法会抛出未检查异常,与get()方法不同的是join()方法不允许被中断。
// 可中断,可设置超时时间
public T get() throws InterruptedException, ExecutionException {...}
public T get(long timeout, TimeUnit unit) throws InterruptedException,
                ExecutionException, TimeoutException {...}
/**
* 不可中断
*/
public T join() {...}

3.CompletionStage的方法使用说明

CompletionStage表示一个任务的执行阶段,每个任务都会返回一个CompletionStage对象,可以对多个CompletionStage对象进行串行、并行或者聚合的方式来进行下阶段的操作,也就是说实现异步任务的回调功能。CompletionStage总共提供了38个方法来实现多个CompletionStage任务的各种操作, 接下来我们就针对这些方法分类来了解一下。

以下类型均有三种使用方式:

  • thenAccept:方法名不带Async的使用主线程同步执行回调函数,不做异步处理
  • thenAcceptAsync:方法名带Async,但是无executor参数的,使用默认线程池ForkJoinPool.commonPool异步执行任务
  • thenAcceptAsync:方法名带Async,有executor参数的,使用自定义线程池异步执行任务

3.1 纯消费类型

  • 依赖单个任务完成(thenAccept):由上一个CompletionStage任务执行完成的结果传递到action进行回调处理,即仅仅消费了上一个CompletionStage任务的返回值,回调处理结果无返回值。
// 不使用线程池,仅依赖当前线程执行,不做异步
public CompletionStage<Void> thenAccept(Consumer<? super T> action);
// 使用默认线程池ForkJoinPool.commonPool执行任务
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
// 使用自定义线程池执行任务
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture.supplyAsync(() -> "this is supplyAsync")
        .thenAcceptAsync((result) -> {
            log.info("{} thenAcceptAsync", result);
        }).join();

// 输出结果:this is supplyAsync thenAcceptAsync

依赖两个任务都完成(thenAcceptBoth):两个CompletionStage任务并发执行,必须都完成了才执行action回调处理,即仅仅消费了两个CompletionStage任务的返回值,回调处理结果无返回值。

/**
* 额外多了CompletionStage参数表示CompletionStage任务依赖的另一个CompletionStage任务
* action接收两个参数,分别表示两个CompletionStage任务的返回值
*/
public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,
                            BiConsumer<? super T, ? super U> action);
// 原理同上,使用默认线程池执行异步任务
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
                            BiConsumer<? super T, ? super U> action);
// 原理同上,使用自定义线程池执行异步任务
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
                            BiConsumer<? super T, ? super U> action, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture<String> cf311 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf311");
CompletableFuture<String> cf312 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf312");
cf311.thenAcceptBothAsync(cf312, (r1, r2) -> {
   log.info("{} and {}", r1, r2);
}).join();
// 输出结果:this is supplyAsync cf311 and this is supplyAsync cf312

依赖两个任务中的任何一个完成(acceptEither):两个CompletionStage任务并发执行,只要其中一个先完成了就携带返回值执行action回调处理,即仅仅消费了优先完成的CompletionStage任务的返回值,回调处理结果无返回值。

/**
* 类似thenAcceptBothAsync,只不过acceptEither只需两个任务中的其中一个完成即可回调action
* action中的值为两个任务中先执行完任务的返回值
*/
public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,
                             Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,
                             Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,
                             Consumer<? super T> action, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture<String> cf311 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf311");
CompletableFuture<String> cf312 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf312");
cf311.acceptEitherAsync(cf312, (r) -> {
    log.info(r); // 输出结果:this is supplyAsync cf311或cf312
}).join();

3.2 有返回值类型

依赖单个任务完成(thenApply):由上一个CompletionStage任务执行完成的结果传递到action进行回调处理,即不止消费了上一个CompletaionStage任务的返回值,同时回调处理结果也有返回值

public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture<String> cf32 = CompletableFuture.supplyAsync(() -> "this is supplyAsync")
        .thenApplyAsync(result -> result + " and thenApplyAsync");
log.info(cf32.join());  // 输出结果:this is supplyAsync and thenApplyAsync

依赖两个任务都完成(thenCombine):两个CompletionStage任务并发执行,必须都完成了才执行action回调处理,即不止消费了两个CompletaionStage任务的返回值,同时回调处理结果也有返回值。

public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,
                             BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,
                             BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,
                             BiFunction<? super T,? super U,? extends V> fn, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture<String> cf321 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf321");
CompletableFuture<String> cf322 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf322");
CompletableFuture<String> thenCombineFuture = cf321.thenCombineAsync(cf322, (r1, r2) -> {
    return r1 + " and " + r2;
});
log.info(thenCombineFuture.join());
// 输出结果:this is supplyAsync cf321 and this is supplyAsync cf322

依赖两个任务中的任何一个完成(applyToEither):两个CompletionStage任务并发执行,只要其中一个任务执行完成就会action回调处理,即不止消费了优先完成的CompletionStage的返回值,同时回调处理结果也有返回值。

// 原理同3.1的acceptEither,只不过applyToEither任务执行完成会返回一个带有返回值的CompletionStage
public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,
                             Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,
                             Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,
                             Function<? super T, U> fn, Executor executor);

// ====================================demo华丽分割线============================================

CompletableFuture<String> cf321 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf321");
CompletableFuture<String> cf322 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf322");
CompletableFuture<String> thenCombineFuture = cf321.applyToEitherAsync(cf322, (r) -> {
    return r;
});
log.info(thenCombineFuture.join());
// 输出结果:this is supplyAsync cf321或cf322

3.3 不消费也不返回类型

依赖单个任务完成(thenRun):单个CompletionStage任务执行完成回调action处理,即执行action回调方法无参数,回调处理结果也无返回值。

// 上一个CompletionStage任务执行完成后直接回调action处理,无返回值
public CompletionStage<Void> thenRun(Runnable action);
// 同上,使用默认线程池执行action处理
public CompletionStage<Void> thenRunAsync(Runnable action);
// 同上,使用自定义线程池执行action处理
public CompletionStage<Void> thenRunAsync(Runnable action, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture.runAsync(() -> {
    // TODO
}).thenRunAsync(() -> {
    log.info("this is thenRunAsync");  // 输出结果:this is thenRunAsync
}).join();

依赖两个任务都完成(runAfterBoth):两个CompletionStage任务并发执行,必须两个任务都完成才执行action回调处理,即执行action回调方法无参数,回调处理结果也无返回值。

// 原理同3.1的thenAcceptBoth,只不过runAfterBoth的action回调处理不接收参数且任务执行完成无返回值
public CompletionStage<Void> runAfterBoth(CompletionStage<?> other, Runnable action);
// 同上,使用默认线程池执行action处理
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action);
// 同上,使用自定义线程池执行action处理
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture<String> cf331 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf331");
CompletableFuture<String> cf332 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf332");
cf331.runAfterBoth(cf332, () -> {
    log.info("this is runAfterBoth");
}).join();
// 输出结果:this is runAfterBoth

依赖两个任务中的任何一个完成(runAfterEither):两个CompletionStage任务并发执行,只需其中任何一个任务完成即可回调action处理,即执行action回调方法无参数,回调处理结果也无返回值。

public CompletionStage<Void> runAfterEither(CompletionStage<?> other, Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture<String> cf331 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf331");
CompletableFuture<String> cf332 = CompletableFuture.supplyAsync(() -> "this is supplyAsync cf332");
cf331.runAfterEitherAsync(cf332, () -> {
    log.info("this is runAfterEitherAsync");
}).join();
// 输出结果:this is runAfterEitherAsync

3.4 组合类型

thenCompose:存在先后关系的两个任务进行串行组合,由第一个CompletionStage任务执行结果作为参数传递给第二个CompletionStage任务,最终返回第二个CompletionStage。

public <U> CompletionStage<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);
public <U> CompletionStage<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn);
public <U> CompletionStage<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture<String> supplyFuture = CompletableFuture.supplyAsync(() -> {
    return "this is supplyAsync";
});
CompletableFuture<String> thenComposeFuture = supplyFuture.thenComposeAsync((r) -> {
    return CompletableFuture.supplyAsync(() -> {
        return r + " and this is thenComposeAsync";
    });
});
log.info(thenComposeFuture.join());
// 输出结果:this is supplyAsync and this is thenComposeAsync

3.5 任务事件类型

CompletionStage接口也支持类似我们常用的try-catch-finally中的finally的作用,无论这个任务的执行结果是正常还是出现异常的情况,都必须要去执行的一个代码块。在CompletionStage接口提供了以下两种接口回调的形式(whenComplete、handle),并支持主线程同步执行同时也支持使用默认线程池,或者使用自定义线程池去异步执行最终的回调处理。例如我们一个事务操作,无论这段代码执行是否成功,我们都必须要去关闭事务。

任务完成事件(whenComplete):结果无返回值,若出现异常执行完whenComplete回调处理完成后将中断主线程的运行

// 1.whenComplete回调函数中Throwable对象不对空代表出现异常,为空则表示无异常
public CompletionStage<T> whenComplete(BiConsumer<? super T, ? super Throwable> action);
public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action);
public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture<String> whenCompleteFufute = CompletableFuture.supplyAsync(() -> {
    int a = 0;
    int b = 100 / a;
    return "this is supplyAsync normal";
}).whenCompleteAsync((r, th) -> {
    if (th != null) {
        log.error("this is whenCompleteAsync error");
    }
    else {
        log.info("this is whenCompleteAsync success");
    }
});
log.info(whenCompleteFufute.join());  // 输出结果:this is whenCompleteAsync error

任务完成回调事件(handle):结果有返回值,若出现异常执行完handle回调处理完成后将继续执行主线程的后续操作,不中断主线程运行

// 2.handle回调函数中Throwable对象不对空代表出现异常,为空则表示无异常
public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor);

// ====================================demo华丽分割线============================================
CompletableFuture<String> whenCompleteFufute = CompletableFuture.supplyAsync(() -> {
    int a = 0;
    int b = 100 / a;
    return "this is supplyAsync normal";
}).handleAsync((r, th) -> {
    if (th != null) {
        return "this is handleAsync error";
    }
    else {
        return "this is handleAsync success";
    }
});
log.info(whenCompleteFufute.join());
// 输出结果:this is handleAsync error
log.info("main thread is running");
// 输出结果:main thread is running

4.CompletionStage异常处理方法

exceptionally:只要是个程序,就会有异常出现的情况,例如一个CompletionStage任务,如果执行过程中出现异常,我们为了保证异常情况下程序能够正常处理业务逻辑,那么在这里我们就可以使用exceptionally进行异常回调处理。当CompletionStage任务出现异常时就会触发回调exceptionally,否则CompletionStage任务正常执行业务不进行异常回调处理。

public CompletionStage<T> exceptionally(Function<Throwable, ? extends T> fn);

// ====================================demo华丽分割线============================================
CompletableFuture<String> exceptionallyFuture = CompletableFuture.supplyAsync(() -> {
    int a = 0;
    int b = 10 / a;  // 除数为0将抛异常
    return "this is supplyAsync normal";
}).exceptionally(th -> {
    log.error("exception:{}", th.getMessage());
    return "this is exceptionally";
});
log.info(exceptionallyFuture.join());  // 输出结果:this is exceptionally

:以下这两种情况可能大家在实际开发过程中会比较少见,但还是得在这里做个提醒,以免到最后准备不充分出现设计上的缺陷。

  • 当whenCompleteAsync与exceptionally同时使用时,若出现异常情况,由于exceptionally有返回值,所以优先执行whenCompleteAsync,后执行exceptionally。
  • 当handleAsync与exceptionally同时出现时,由于handleAsync已经包含了exceptionally的所有操作,即handleAsync回调有返回值,且有Throwable异常对象能够进行异常处理,所以这两者同时出现时exceptionally将失效。

5.方法类型总结

根据以上的方法我们可以总结出这些任务其实就分为三大类,相当于通过CompletionStage的回调机制来实现多个任务串、多个任务并行、多个任务聚合的操作,因此CompletableFuture对于异步任务的处理提供了更加强大的编程模型。所以说java8提供的CompletableFuture类相对原来的Future接口来说提供了一些链式的编程,省去了我们很多异步任务回调操作复杂的步骤,让我们这些码农们能够有更高的效率输出产品。

到此这篇关于Java8并发新特性CompletableFuture的文章就介绍到这了,更多相关Java8 CompletableFuture内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Java8 自定义CompletableFuture的原理解析

    目录 Java8 自定义CompletableFuture原理 CompleteFuture简单使用 下面简单介绍用法 Java8 自定义CompletableFuture原理 Future 接口 的局限性有很多,其中一个就是需要主动的去询问是否完成,如果等子线程的任务完成以后,通知我,那岂不是更好? public class FutureInAction3 { public static void main(String[] args) { Future<String> future = i

  • 详解Java8 CompletableFuture的并行处理用法

    目录 前言 场景 用法 1.在线API 2.编写在线API查询 3.编写查询服务 4.编写测试接口 5.效果 6.CompletableFuture并行查询 7.编写测试接口 8.CompletableFuture效果 思考 前言 工作中你可能会遇到很多这样的场景,一个接口,要从其他几个service调用查询方法,分别获取到需要的值之后再封装数据返回. 还可能在微服务中遇到类似的情况,某个服务的接口,要使用好几次feign去调用其他服务的方法获取数据,最后拿到想要的值并封装返回给前端. 这样的场

  • Java8新的异步编程方式CompletableFuture实现

    一. Future JDK 5引入了Future模式.Future接口是Java多线程Future模式的实现,在java.util.concurrent包中,可以来进行异步计算. Future模式是多线程设计常用的一种设计模式.Future模式可以理解成:我有一个任务,提交给了Future,Future替我完成这个任务.期间我自己可以去做任何想做的事情.一段时间之后,我就便可以从Future那儿取出结果. Future的接口很简单,只有五个方法. public interface Future<

  • Java8 CompletableFuture详解

    Java 8来了,是时候学一下新的东西了.Java 7和Java 6只不过是稍作修改的版本,而Java 8将会发生重大的改进.或许是Java 8太大了吧?今天我会给你彻底地解释JDK 8中的新的抽象 – CompletableFuture.众所周知,Java 8不到一年就会发布,因此这篇文章是基于JDK 8 build 88 with lambda support的.CompletableFuture extends Future提供了方法,一元操作符和促进异步性以及事件驱动编程模型,它并不止步

  • 深入学习java8 中的CompletableFuture

    目录 1 前言 2 简单使用 3 异步处理 3.1 thenApply 3.2 thenAccept 和 thenRun 3.3 exceptionally 异常处理 3.4 whenComplete 方法完成之后 3.5 handle 4 处理组合 4.1 任务均完成后组合 4.2 任一任务完成 4.3 任务处理结果 4.4 所有或者任何 5 总结 1 前言 在项目开发中,异步化处理是非常常见的解决问题的手段,异步化处理除了使用线程池之外,还可以使用 CompletableFuture 来实现

  • Java8 使用工厂方法supplyAsync创建CompletableFuture实例

    目录 使用工厂方法 supplyAsync创建 CompletableFuture 对比 对CompletableFuture async的理解 目前为止我们已经了解了如何通过编程创建 CompletableFuture 对象以及如何获取返回值,虽然看起来这些操作已经比较方便,但还有进一步提升的空间, CompletableFuture 类自身提供了大量精巧的工厂方法,使用这些方法能更容易地完成整个流程,还不用担心实现的细节. 可以看到我们使用new Thread的方式,显然是不恰当的. 使用工

  • Java8 CompletableFuture 异步执行操作

    目录 1.简介 2.异步执行 3.守护线程 4.处理执行结果 1.简介 CompletableFuture 是 JDK8 提供的一个异步执行工具. 示例1: public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { for (int i

  • Java8通过CompletableFuture实现异步回调

    目录 1 什么是CompletableFuture? 2 为什么会有CompletableFuture ? 3 CompletableFuture 简单使用 4 CompletableFuture 源码分析 4.1 创建异步任务 4.2 异步任务回调 4.3 异步任务组合 前言: java5为我们提供了Callable和Future,使我们可以很容易的完成异步任务结果的获取,但是通过Future的get获取异步任务结果会导致主线程的阻塞,这样在某些场景下是非常消耗CPU资源的,进而Java8为我

  • Java8并发新特性CompletableFuture

    目录 1.CompletableFuture是什么? 2.CompletableFuture的方法使用说明 2.1 CompletableFuture类提供几个静态方法来进行异步操作 2.2 获取异步任务执行结果的方法 get()/join() 3.CompletionStage的方法使用说明 3.1 纯消费类型 3.2 有返回值类型 3.3 不消费也不返回类型 3.4 组合类型 3.5 任务事件类型 4.CompletionStage异常处理方法 5.方法类型总结 1.CompletableF

  • Java8中新特性Optional、接口中默认方法和静态方法详解

    前言 毫无疑问,Java 8是Java自Java 5(发布于2004年)之后的最重要的版本.这个版本包含语言.编译器.库.工具和JVM等方面的十多个新特性. Java 8是Java的一个重大版本,有人认为,虽然这些新特性领Java开发人员十分期待,但同时也需要花不少精力去学习.下面本文就给大家详细介绍了Java8中新特性Optional.接口中默认方法和静态方法的相关内容,话不多说了,来一起看看详细的介绍吧. Optional Optional 类(java.util.Optional) 是一个

  • Kotlin 接口与 Java8 新特性接口详解

    前言 在看一本关于高性能编程的时候发现 Java8 中关于接口的新特性的介绍,这个特性是真的棒,解决了一个接口中有多个方法,但并不想实现该接口的类都去实现所有的方法,简单的说就是在类需要的情况再去重写接口.所以有了以下的特性出现. 接口增强 在 Java8 的中接口特性中增加以下俩种特性: 在接口中可以使用 default 关键字修饰默认方法或扩展方法,抽象方法因为其特性的原因无法使用 接口可以使用 static 声明为静态方法,可以通过类直接调用Android Studio 中使用 Java8

  • 详解Java8新特性之interface中的static方法和default方法

    为什么要单独写个Java8新特性,一个原因是我目前所在的公司用的是jdk8,并且框架中用了大量的Java8的新特性,如上篇文章写到的stream方法进行过滤map集合.stream方法就是接口Collection中的default方法.所以准备专门写写关于java8新特性的文章,虽然现在10已经发布了.但还是要认真的去了解下新版本的变化. static方法 java8中为接口新增了一项功能:定义一个或者更多个静态方法.用法和普通的static方法一样. 代码示例 public interface

  • java8新特性之stream的collect实战教程

    1.list转换成list 不带return方式 List<Long> ids=wrongTmpList.stream().map(c->c.getId()).collect(Collectors.toList()); 带return方式 // spu集合转化成spubo集合//java8的新特性 List<SpuBo> spuBos=spuList.stream().map(spu -> { SpuBo spuBo = new SpuBo(); BeanUtils.c

  • java8新特性之方法引用示例代码

    简介 方法引用是java8的新特性之一, 可以直接引用已有Java类或对象的方法或构造器.方法引用与lambda表达式结合使用,可以进一步简化代码. 方法引用的使用场景 我们用Lambda表达式来实现匿名方法.但有些情况下,我们用Lambda表达式仅仅是调用一些已经存在的方法,除了调用动作外,没有其他任何多余的动作,在这种情况下,我们倾向于通过方法名来调用它,而Lambda表达式可以帮助我们实现这一要求,它使得Lambda在调用那些已经拥有方法名的方法的代码更简洁.更容易理解.方法引用可以理解为

  • Java8中接口的新特性使用指南

    目录 前言 编写测试类ComepareTest 第一种情况,一个类实现了接口的同时又继承了一个父类 情况二 情况三 总结 前言 在Java8中接口中不再只有抽象方法,还可以有静态方法以及默认方法,此时的接口更像是一个类.我们一起来看看如何使用吧~ Java8中,可以为接口添加静态方法和默认方法. 静态方法:使用static关键字修饰.可以通过接口直接调用静态方法,并执行其方法体 默认方法:使用default关键字修饰.可以通过类来调用 直接看代码吧 package com.nanfeng.dem

  • Java8新特性之线程安全日期类

    LocalDateTime Java8新特性之一,新增日期类. 在项目开发过程中经常遇到时间处理,但是你真的用对了吗,理解阿里巴巴开发手册中禁用static修饰SimpleDateFormat吗 通过阅读本篇文章你将了解到: 为什么需要LocalDate.LocalTime.LocalDateTime[java8新提供的类] Java8新的时间API的使用方式,包括创建.格式化.解析.计算.修改 可以使用Instant代替 Date,LocalDateTime代替 Calendar,DateTi

  • Java8新特性Stream流实例详解

    什么是Stream流? Stream流是数据渠道,用于操作数据源(集合.数组等)所生成的元素序列. Stream的优点:声明性,可复合,可并行.这三个特性使得stream操作更简洁,更灵活,更高效. Stream的操作有两个特点:可以多个操作链接起来运行,内部迭代. Stream可分为并行流与串行流,Stream API 可以声明性地通过 parallel() 与sequential() 在并行流与顺序流之间进行切换.串行流就不必再细说了,并行流主要是为了为了适应目前多核机器的时代,提高系统CP

  • JAVA8 十大新特性详解

    "Java is still not dead-and people are starting to figure that out." 本教程将用带注释的简单代码来描述新特性,你将看不到大片吓人的文字. 一.接口的默认方法 Java 8允许我们给接口添加一个非抽象的方法实现,只需要使用 default关键字即可,这个特征又叫做扩展方法,示例如下: 复制代码 代码如下: interface Formula {    double calculate(int a); default do

随机推荐