JAVA异步任务-CompletableFuture

【JAVA8】CompletableFuture使用详解 CompletableFuture!让你的代码免受阻塞之苦! 灵活的使用`CompletableFuture`可以让我们感受java8的异步编程之美! 阅读详情

1.概述

在jdk1.8中,引入了CompletableFuture,它扩展了Future和CompletionStage,可以在任务完成后触发回调,实现异步调用。在此之前若要设置回调一般会使用guava的ListenableFuture,但引入回调之后会陷入无穷的回调地狱中,导致编码难以阅读和理解。CompletableFuture对Future进行了扩展,可以通过设置回调的方式处理计算结果,同时也支持组合,支持任务编排,在一定程度上解决了回调地狱和代码难以阅读问题。本文将分析CompletableFuture的使用及实现原理。

2.案例分析

2.1 CompletableFuture使用

2.1.1 创建CompletableFuture

1.利用 runAsync(Runnable runnable)创建
runAsync方法入参是Runnable、executor,如果入参有executor,则使用executor来执行异步任务。需要注意的是,runAsync方法只执行方法里面内容,不携带返回结果。

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

//使用runAsync(Runnable runnable)创建CompletableFuture对象如下
   CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> {
   
   
            try {
   
   
                //Thread.sleep(1000);
                System.out.println("runAsync  " + Thread.currentThread().getName());
            } catch (Exception e) {
   
   
                e.printStackTrace();
            }
        });

//使用runAsync(Runnable runnable, Executor executor)创建CompletableFuture对象
       final ExecutorService executorService = Executors.newFixedThreadPool(2);
        CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> {
   
   
            try {
   
   
                //Thread.sleep(1000);

            } catch (Exception e) {
   
   
                e.printStackTrace();
            }
            System.out.println("runAsync  " + Thread.currentThread().getName());
        }, executorService);

2.利用supplyAsync(Supplier supplier)创建

supplyAsync(Supplier supplier)异步执行并返回结果的任务,适合需要返回值的场景。


public static <U> CompletableFuture<U>  supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U>  supplyAsync(Supplier<U> supplier, Executor executor)

//使用supplyAsync(Runnable runnable)创建CompletableFuture对象如下
      CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
   
   
            try {
   
   
                //Thread.sleep(5000);
            } catch (Exception e) {
   
   
                e.printStackTrace();
            }
            System.out.println("supplyAsync  " + Thread.currentThread().getName());
            return "hello";
        });



//使用supplyAsync(Runnable runnable,Executor executor)创建CompletableFuture对象如下
 CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
   
   
            try {
   
   
                //Thread.sleep(5000);
            } catch (Exception e) {
   
   
                e.printStackTrace();
            }
            System.out.println("supplyAsync  " + Thread.currentThread().getName());
            return "hello";
        }, executorService);


2.1.2 完成complete和取消cancel操作

complete(V value):手动完成CompletableFuture,强制设置返回结果;
cancel(boolean mayInterruptIfRunning):取消任务,入参为true表明中断正在执行的任务;

//强制设置返回结果,即使任务有返回结果,也会被complete强制返回结果替代
 public static String complete() throws ExecutionException, InterruptedException {
   
   
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync((
Java8异步类CompletableFuture详解 JDK8引入了一个新的类CompletableFuture 阅读详情

相关推荐

Java异步编程利器:CompletableFuture详解

‌CompletableFuture‌是Java 8中引入的一个类,它实现了Future和CompletionStage接口,用于支持异步编程和非阻塞操作。CompletableFuture提供了丰富的API,使得并发任务的处理变得简单而高效,能够轻松创建、组合和链式调用异步操作,无需关心底层线程管理,从而提升了程序的响应速度和资源利用率‌。

who_im_i的博客 2420

Java CompletableFuture异步任务详解

在现代的应用程序开发中,处理并发任务是一项常见的需求。Java提供了CompletableFuture类来处理异步任务,它提供了一种简单而强大的方式来处理并发编程。本文将介绍CompletableFuture的基本用法和一些注意事项。

一碗清深的博客 337

Java8中CompletableFuture实现异步任务编排以及示例

在上面使用Future以及进行并发流程控制之外,可使用Java8新增的CompletableFuture。Future的局限性,它没法直接对多个任务进行链式、组合等处理,需要借助并发工具类才能完成,实现逻辑比较复杂。CompletableFuture是对Future的扩展和增强。CompletableFuture实现了Future接口,并在此基础上进行了丰富的扩展,完美弥补了Future的局限性,同时CompletableFuture实现了对任务编排的能力。

BADAO_LIUMANG_QIZHI的博客 2380

Apollo学习笔记(4)坐标系

百度Apollo项目用到了多种坐标系,其中帮助文档提及的坐标系包括: 全球地理坐标系(The Global Geographic coordinate system ) 局部坐标系—东-北-天坐标(The Local Frame – East-North-Up,ENU) 车身坐标系—右-前-天坐标(The Vehicle Frame —Right-Forward-Up,RFU) 车身坐标系—前-左-天坐标(The Vehicle Frame —Front-Left-Up,FLU) 还有一种Frenet坐标

qq_24649627的博客 5801

【原创工具 | OpenCV-CamCalib】一个基于 OpenCV 的自动化相机数据采集和标定程序

一个基于OpenCV的自动化相机数据采集和标定程序。系统内置相机地址默认为 0。

XavierJ的博客 2701

DAC8568控制器实战:如何用STM32实现多通道同步输出(附完整代码)

本文详细介绍了如何使用STM32微控制器驱动TI的DAC8568多通道DAC控制器,实现高精度的多通道同步模拟信号输出。内容涵盖硬件设计要点、SPI时序精准配置、驱动层命令构建,并重点解析了通过LDAC引脚实现同步更新的核心策略,提供了完整的代码框架和实战案例,帮助工程师快速解决多通道同步输出的工程难题。

weixin_29179311的博客 183

浅谈专项测试之弱网络测试

浅谈专项测试之弱网络测试 一.弱网络测试背景 移动端产品的使用并非完全都是在流畅的wifi环境,大部分用户主要使用4G,3G,2G等网络,另外因为移动端产品使用的场景多变,如进公交,上地铁,坐电梯,使得弱网测试显得尤为重要。考虑到各种场景的客户端展示及容错,提升产品的印象和用户体验,提高产品的健壮性,弱网测试必不可少。 二.弱网络测试建议 网下需要进行功能点测试,无网络测试,网络切换测试等,测试过程除了关注功能点的实现,还应关注用户体验等各个方面 三.弱网络测试通用功能点总结 四.弱网络测试用例实例

ITstudy001的博客 1014

NL2SQL实践系列(1):深入解析Prompt工程在text2sql中的应用技巧

NL2SQL实践系列(1):深入解析Prompt工程在text2sql中的应用技巧

丨汀、的博客 4333

原理和代码解读:用Diffusion Models高清图像修复(Image Inpainting)

在最近的Diffusion Models应用中,Image Inpainting+ControlNet/Lora等工作在模特衣服生成、家居场景重建等场景中得到了广泛的应用。这篇博客主要介绍Diffusion Models如何在修复高清图像的。

沉迷单车的追风少年 2499

面向业务角色的 SAP Fiori Space 与 Page 创建全流程实战指南

业务角色导航设计:从Space与Page规划到实施 摘要:本文探讨了SAP S/4HANA Cloud和BTP ABAP环境中基于业务角色的导航设计方法。传统Fiori Launchpad的Group+Tile模式存在应用堆积问题,而新的Space与Page模型将导航按工作领域(如应付会计、销售代表)组织,每个Space包含多个任务导向的Page。文章详细介绍了从业务角色建模到Space/Page创建、分配的完整流程,包括核心概念解析、规划思路和具体操作步骤。重点阐述了如何根据业务需求选择创建方式(基于预交

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 190

化工仿真软件:gPROMS二次开发_(1).gPROMS基础知识

在gPROMS中,模型是通过定义变量、参数和方程来创建的。模型可以是简单的单元操作,如换热器、反应器,也可以是复杂的系统,如整个化工流程。变量是模型中表示状态或输出的量。在gPROMS中,变量需要显式定义其类型和单位。# 定义变量VAR# 温度变量,单位为K# 压力变量,单位为Pa# 组分摩尔分数,数组变量参数是模型中表示常量或初始条件的量。参数同样需要定义其类型和单位。# 定义参数PAR# 理想气体常数,单位为J/(mol·K)# 反应器体积,单位为m^3# 初始摩尔数。

kkchenjj的博客 624

深度学习工具包 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")

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Statistics and Machine Learning Toolbox

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

上一篇: SpringBoot全局异常处理-原理分析
下一篇: 详解Redis的五种基本数据类型(String、List、Hash、Set、ZSet)
程可爱
博客等级 码龄11年 220粉丝 130原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值