【Java】Java 8的CompletableFuture介绍

Java8 CompletableFuture底层实现及使用详解 该方法的区别在于,它将任务串联起来,可以实现多个异步操作的链式调用。然后,通过thenApply方法将该CompletableFuture对象转换为一个新的CompletableFuture对象,用于异步执行一个返回整数类型的任务,转换函数是将字符串长度作为结果返回。thenCompose方法接收一个Function类型的参数,该函数用于将一个CompletableFuture对象的结果作为下一个CompletableFuture对象的输入,并返回一个新的CompletableFuture对象。 阅读详情

【参考】

1. non-blocking操作

这里的asynchronous操作即non-blocking操作,非阻塞式的操作,表示主线程可以提交task给独立的线程,独立的线程可以自行运行该task,主线程则会继续运行别的业务逻辑代码。

提交的task可以是Runnable实现,也可以是Callable实现(有返回值):

2. 通过ExecutorService进行task的提交

ExecutorService提交Callable的task后,可以通过future.get()拿到task的执行结果,get()方法是阻塞式的获取结果,即如果该task还没有执行完毕,此时main thread需要等待,直到task执行完毕并返回结果。

ExecutorService存在的问题是如果一次性提交了4个tasks,那么在拿结果的时候,需要依次拿(future.get()),但这个方法是阻塞式的,假如task3或4提交完成了,也需要等待main thread从task1先拿到结果:

更为复杂的例子,假如处理1个order分5个步骤,即拿到order、补齐order必要的属性、付款、发送order,最后是邮件发送:

代码如下,因为get是阻塞式的,所以for循环里order1的处理,会影响后续order的速度,因为main thread有可能会卡在order1,而这时候后续的order可能已经处理完毕,这也使得使用多线程处理变的没有必要,因为order的处理顺序依旧是线性执行的:

publicvoidorderLifeCycle(){
    ExecutorService service = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 5; i ++) {
        try {
            Future<Order> future = service.submit(getOrderTask());
            Order order = future.get(); // 阻塞

            Future<Order> future1 = service.submit(enrichTask(order));
            order = future1.get(); // 阻塞

            Future<Order> future2 = service.submit(performPaymentTask(order));
            order = future2.get(); // 阻塞

            Future<Order> future3 = service.submit(dispatchTask(order));
            order = future3.get(); // 阻塞

            Future<Order> future4 = service.submit(sendEmailTask(order));
            order = future4.get(); // 阻塞

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

而我们想要的效果是,order本身的flow是一个整体(虽然它可能分了很多个Callable步骤),但order与order之间,不应该相互等待,比如order1可以由某个线程执行并正在执行sendEmail方法,而order2可以由另外一个线程执行并正在执行payment方法,即每个order都是独立的流水线(independent flows):

3. CompletableFuture

可以使用CompletableFuture来实现上述想要的期望:

publicvoidorderSubmit(){
    for (int i =0; i < 5; i ++) {
        CompletableFuture.supplyAsync(() -> getOrder())
                .thenApply(order -> enrich(order))
                .thenApply(order -> performPayment(order))
                .thenApply(order -> dispatch(order))
                .thenAccept(order -> sendEmail(order));
    }
}

3.1 supplyAsync方法

supplyAsync()方法是CompletableFuture中的static方法,从定义可以看到它接受Supplier接口的参数,Supplier接口位于java的java.util.function包中,也是Java 8引入的函数式接口,与之配套的还有另外两个接口:Function和Consumer,具体来说:

  • Supplier接口:不接收参数,但返回一个对象(用消息组件来类比,可以看作是生产者)。

  • Function接口:接收参数后,再返回另一个对象(用消息组件来类比,即接收一个消息,进行处理后再发送至另一个地方)。

  • Consumer接口:接收参数,但不会再返回对象(用消息组件来类比,可以看作是消费者)。

publicstatic <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier){
    return asyncSupplyStage(ASYNC_POOL, supplier);
}

在我们order的例子中,supplyAsync(() -> getOrder())即通过线程来处理拿到一个order的业务,然后返回。

supplyAsync()除了接收suppilier函数外,还可接收线程池,即传入自定义的线程池来处理。如果没有指定,则会创建一个:Executor ASYNC_POOL = USE_COMMON_POOL ? ForkJoinPool.commonPool() : new ThreadPerTaskExecutor()。

3.2 thenApply方法

thenApply()方法接收的是Function接口,Function接口在上面介绍过了,它能接收一个参数,并返回一个结果。在我们的order例子中,它接收了getOrder()返回的order参数,并进行处理后(通过方法enrich(order))再返回order结果。

public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn){
    return uniApplyStage(null, fn);
}

与thenApply()方法类似的还有一个方法叫thenApplyAsync(),两者的区别是:

  • thenApply()会沿用上一个方法相同的线程。

  • thenApplyAsync()会使用另一个线程来执行方法体内的task,也可以传入线程池。

具体来说,假设我们的getOrder()方法是IO开销比较大的(比如需要从DB里查询),而我们的enrich(order)方法只是一些计算相关,即CPU开销比较大,那么我们在执行的时候,可能会用两个不同的线程池来执行,IO开销大的可以设置线程数多一些。

publicvoidorderSubmit(){
    ExecutorService cpuService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    ExecutorService ioService = Executors.newCachedThreadPool();

    for (int i =0; i < 5; i ++) {
        CompletableFuture.supplyAsync(() -> getOrder(), ioService)
                .thenApplyAsync(order -> enrich(order), cpuService)
                .thenApply(order -> performPayment(order))
                .thenApply(order -> dispatch(order))
                .thenAccept(order -> sendEmail(order));
    }
}

3.3 thenAccept方法

thenAccept()方法接收Comsumer接口(接收一个参数,但没有返回值)。

与thenAccept()方法相对的,有thenAcceptAsync()方法,同样的,该方法能传入一个线程池,使得方法里的task可以在传入的线程池中进行提交执行。

public CompletableFuture<Void> thenAccept(Consumer<? super T> action){
    return uniAcceptStage(null, action);
}

3.4 exceptionally方法

异常处理。如果getOrder()或enrich(order)或performPayment(order)中出现了一些异常,我们可以使用exceptionally()来捕获异常,然后返回别的类,这样dispatch(order)方法就知道在前面的步骤中出现了异常(比如拿到参数后先进行类型判断,是normal的Order还是FailedOrder。

CompletableFuture.supplyAsync(() -> getOrder(), ioService)
        .thenApplyAsync(order-> enrich(order), cpuService)
        .thenApply(order-> performPayment(order))
        .exceptionally(e-> newFailedOrder())
        .thenApply(order-> dispatch(order))
        .thenAccept(order-> sendEmail(order));

3.5 其它方法,如thenCombine

这个可以连接两个stage的结果。但这个写起来比较复杂,推荐java的另一个框架,叫Reactor框架,实现起来可能更加便捷,代码也更易读。

4. 总结

CompletableFuture中suplyAsnc()或thenApply()或thenAccept()都不会阻塞main thread,如果我们有100个order flow需要处理,那么每个order的流程都不会相互阻塞。

Java8学习计划--关于多核多线程并发编程-Java8-CompletableFuture 4的介绍 零零散散接近一个月的课余时间,学完Java8InAction和Guava,感触很多,收获也很大,特别开心,接下来会利用空余时间学习Spark,希望自己在技术上慢慢积累,越来越从容。对于Java8 最大的改变是lambda表达式 Collecotors CompletableFutures等 Funtional Programing.的思想真的很强大下面介绍Java8 CompletableFutu... 阅读详情

相关推荐

java8 CompletableFuture实现原理详解

Java 8新增加了CompletableFuture类,该类提供了非常强大的Future扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。 本文接下来首先介绍其基本用法,之后介绍其实现原理。 文章目录1、CompletableFuture2、实现原理 1、CompletableFuture CompletableFuture实现了Future和CompletionStage两个接口。 Futur

龚厂长的博客 4280

JDK8 并发新特性学习 (一) CompletableFuture

JDK8 并发新特性学习 (一) CompletableFutureJDK 8 java.util.concurrent新增加的两个接口和四个类 CompletableFutre.AsynchronousCompletionTask 一个没有方法的装饰接口,用来标识异步的任务 CompletionStage<T> 一个多个异步计算的接口,对多个异步计算进行组合、过滤、异常处理等操作。 Concu

sutonline的博客 717

java8从入门到精通3:completableFuture

明略语音识别引擎 -API文档 时间 版本 作者 变更内容 20200426 1.0 xschao 初版 20200510 1.1 xschao 补充接口部分 20200525 1.2 kundong 增加文件上传接口 20200812 1.3 kundong 增加流式识别功能 20201217 1.4 kundong 增加思必驰引擎识别 文章目录明略语音识别引擎 -API文档简介调用方式1. 服务地址2. 通信协议3. 请求方法响应4. 字符编码5. 数据字段类型定

ykd2020 318

Java的异步编程(三):CompletableFuture的简介和成员变量

一:简介 上文提到了Future是实现异步调用的工具,但是Future存在着使用不便的缺点,Java8中提供了CompletableFuture来完善异步流程; CompletableFuture能够在不同线程中执行回调,也可以将回调作为继续执行的同步函数,还有在异步的任务完成后,可以通过thenAccept、thenApply、thenCompose等方法继续执行,而无需阻塞等待下一步执行; ...

JoshuaXin的博客 1181

cadence—virtuosoic617的使用技巧收集区

cadence使用

qq_33599939的博客 3万+

Cadence SIP Layout 简单教程-第一章

以摄像头模组软硬结合板为例,描述layout的整个完整过程,从而掌握基本技能。 第一章 准备工作 第一节 原理图不用说layout前需要绘制原理图,原理图不在本文讨论范围内,所以列为准备工作。 需要特别说明的是,绘制原理的最终目的是导出网络表,网络表中的重要参数footprint是让layout软件选择正确封装的关键,所以这里讲解一下原理图设置footprint的位置。在原理图中双击零件,...

whp1920的博客 1万+

探秘高并发之java.util.concurrent (二)

本系列关于concurrent的代码示例,是被我分割成了小部分,在系列文章结束以后,我会将较为完整的代码上传,在写的过程中我会参考官方API以及其他牛人的见解,大家有不同的看法可以在下面回复。 这一篇我们继续讲concurrent包下面的接口,本篇讲Callable、 AsynchronousCompletionTask、Completi...

weixin_34344677的博客 136

手把手教你用内核远程call实现64位进程注入(附完整ShellCode示例)

本文深入探讨了在Windows 64位环境下,通过内核态直接操作线程TrapFrame结构实现进程注入的高级技术。文章提供了从驱动框架设计、用户态-内核态通信,到定位修改TrapFrame、编写Shellcode及执行环境恢复的完整实战指南,并附有详细的代码示例,为安全研究人员和开发者提供了绕过用户态检测、实现底层远程代码执行的新思路。

weixin_28396629的博客 352

CompletableFuture之supplyAsync

CompletableFuture之supplyAsync入门用法

m0_63285669的博客 8910

缺陷检测:使用PatchCore训练自己的数据集

必须包含有训练图片(无缺陷图片)、测试图片(缺陷图片)和ground_truth,并且ground_truth必须与对应图片的名称相同。同上一篇结果一样,我的输出为原始图片大小,但是不知道是不是因为图片不是正方形的,导致训练结果不好。编写一个脚本,重新规划数据集的路径规则,但是我稍微写复杂了一点,使用了类来操作。第二种(复杂):编写一个自己的Dataset,参考。第一种(简单):将数据集路径规则改成项目中。返回的必须是一个字典类型,可以阅读。本人此次使用的是第一种方法。运行时,参数部分直接输入。

xiaoxTai的博客 6490

阿里云百炼平台创建智能体-上传文档

阿里云百炼智能体-上传文档文件

weixin_43930851的博客 1365

java中future 用法_Java8的CompletableFuture的用法介绍(附示例)

本篇文章给大家带来的内容是关于Java8的CompletableFuture的用法介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。作为Java 8 Concurrency API改进而引入,本文是CompletableFuture类的功能和用例的介绍。同时在Java 9 也有对CompletableFuture有一些改进,之后再进入讲解。Future计算Future异...

weixin_34928522的博客 1756

基于反事实的因果推理Causal inference based on counterfactuals--一万六千字文献详细解读(因果关系的推理应用)【全文总结】

基于反事实的因果推理Causal inference based on counterfactuals--一万六千字文献详细解读(因果关系的推理应用)【全文总结】---来自一位即将入学的准研一,也希望这篇文章能够激励自己不断走下去!!

qq_46044325的博客 4448

Java8 关于CompletableFuture的介绍

中或或都不会阻塞main thread,如果我们有100个order flow需要处理,那么每个order的流程都不会相互阻塞。这里强调的是这三个方法本身,而不是最终通过get()方法拿结果。因为例子中最后的用的是thenAccept,这里接收的是Comsumer函数,即并没有返回值。这个例子强调的是每组CompletebleFuture之间,是不受影响的。

Java技术攻略的博客 319

LDRA Testbed(TBrun)软件单元测试_实例讲解(对多次调用的函数打桩)

在之前的文章《LDRA Testbed(TBrun)软件单元测试_操作指南》中,已经讲解了如何使用TBrun进行软件单元测试的基本操作步骤。本篇文章将结合实例进一步讲解被测函数中包含多次调用其他函数时,如何对其打桩来实现测试目的(详细的操作流程本文不再重述,若有不清楚的,可以结合之前的操作指南一起来看)。本文以一个被测函数作为示例,讲解了如何使用Testbed(TBrun)对涉及到多次调用其他函数的被测函数进行单元测试。本文的示例可能比较简单,但是思路、方法和流程都是通用的,希望对大家有所帮助。

文章主要涉及嵌入式软件开发、测试、项目管理等,欢迎交流,共同进步。 1470

基于深度学习的鸟类检测识别系统:YOLOv5 + YOLOv8 + YOLOv10 + UI界面 + 数据集

YOLOv5是当前目标检测领域非常流行的模型,具有良好的检测精度和实时推理速度。其网络结构相比前几代YOLO模型进行了优化,尤其是在检测精度和计算效率上有了显著提高。YOLOv5特点高效性:能够在较低的硬件环境下进行实时检测。易于部署和使用:YOLOv5提供了简单的API接口,方便开发者快速集成和使用。优异的精度:在多个数据集上测试,表现出色。本文详细介绍了基于YOLOv5、YOLOv8和YOLOv10的鸟类检测识别系统的设计与实现。

YOLO 1117

java 8 新特性功能和用法介绍03---CompletableFuture基本用法介绍

Java8 CompletableFuture java 8 新增CompletableFuture类简化异步编程的复杂性,提供函数式编程的能力,并且可以通过回调的方式处理计算结果。同时解决了 传统异步编程Future模式的缺点,对于异步执行结果,只能通过等待get操作以及轮询isDone去判断Future是否完成,是非常耗费CPU资源。而CompletableFuture 弥补了Future模式的缺点,在异步的任务完成后,需要用其结果继续操作时,无需等待。可以直接通过thenAccept、thenAppl

weixin_43946605的博客 614

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Java8新特性:CompletableFuture 方法介绍

目录 1.runAsync 和 supplyAsync方法 2.whenComplete、whenCompleteAsync、exceptionally 3. thenApply 、handle thenApply handle 4.thenAccept 、thenRun 方法消费处理结果 thenAccept thenRun 5.thenCombine 、the...

jast 2064

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java 8异步任务类库——CompletableFuture简单介绍和使用

一、直接看代码 package CompletableFuture; import java.util.Random; import java.util.concurrent.CompletableFuture; /** * @author hs * @date 2021/11/26 10:23 * java8新特性 * CompletableFuture就是用于Java中的异步编程。使用CompletableFuture创建的任务,不会阻塞主线程/主线程不需要等待任务完成,极大地提高了程序的性

a123123sdf的博客 573

java8中CompletableFuture异步处理超时的方法

stackoverflow上有一个讨论:Timeout with default value in Java 8 CompletableFuture 其中大家讨论了实现方案 其中的一个解决方案: 原文链接:Asynchronous Timeouts with CompletableFuture 如何实现Asynchronous timeouts Java 8 的 CompletableFuture 并没有 timeout 机制,虽然可以在 get 的时候指定 timeout,但是我们知道get 是一个同步

u013905744的专栏 2万+

Java8新的异步编程方式 CompletableFuture(一)

Future虽然可以实现获取异步执行结果的需求,但是它没有提供通知的机制,我们无法得知Future什么时候完成。要么使用阻塞,在future.get()的地方等待future返回的结果,这时又变成同步操作。要么使用isDone()轮询地判断Future是否完成,这样会耗费CPU的资源。Netty、Guava分别扩展了Java的Future接口,方便异步编程。

风一样 703

java并发系列 - 第30天:JUC中工具类CompletableFuture,必备技能

是java8中新增的一个类,算是对Future的一种增强,用起来很方便,也是会经常用到的一个工具类,熟悉一下。

GitHub质检员 164

Java8 CompletableFuture异步编程

介绍 使用场景 常用异步编程实现方案 - Thread - ExecutorService - CountDownLatch - CyclicBarrier - ForkJoinPool - CompletableFuture 各种实现方案总结 结构 结构梳理 - Future接口 - CompletionStage接口 常用方法 使用示例 1. 基本异步操作 2. 任务链式调用 3. 多个异步任务组合 4. 异常处理 5. 并行执行多个任务 6. 处理返回值的转换

骑个小蜗牛的博客 3603

Java8新特性CompletableFuture详解

thenCombine()被用来当两个独立的Future都完成的时候,用来做一些事情。CompletableFuture 是Java 8 中引入的 Java Future API的扩展,用于 Java 中的异步编程,它可以使我们的任务运行在与主线程分离的其他线程中,并通过回调在主线程中得到异步任务执行状态,包括是否完成,是否异常等信息。我们 使用 thenCompose()组合两个独立的future,假设我们想从一个远程API中获取一个用户的信息,当用户信息可用时,我们想从另外一个服务中获取另外的信息。

qq_42077317的博客 1927

Java CompletableFuture 详解

source: http://www.tuicool.com/articles/UVrMNrN Java CompletableFuture 详解 时间 2016-02-29 16:49:32 colobu bolg 原文  http://colobu.com/2016/02/29/Java-CompletableFuture/ 主题 Java

BalterNotz的博客 2323
上一篇: 牛!华为工程师总结的Java生态知识体系面试必看笔记,太秀了
下一篇: 今年,应届生如何才能拿到大厂1万+月薪开发offer?
Java技术那些事儿
博客等级 码龄5年 2306粉丝 2584原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址