Java实现异步调用
一、创建线程
@Test
public void test0() throws Exception {
System.out.println("main函数开始执行");
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("===task start===");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("===task finish===");
}
});
thread.start();
System.out.println("main函数执行结束");
}
二、Future
jdk8之前的实现方式,在JUC下增加了Future,从字面意思理解就是未来的意思,但使用起来却着实有点鸡肋,并不能实现真正意义上的异步,获取结果时需要阻塞线程,或者不断轮询。
@Test
public void test1() throws Exception {
System.out.println("main函数开始执行");
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("===task start===");
Thread.sleep(5000);
System.out.println("===task finish===");
return 3;
}
});
//这里需要返回值时会阻塞主线程,如果不需要返回值使用是OK的。倒也还能接收
//Integer result=future.get();
System.out.println("main函数执行结束");
System.in.read();
}
三、CompletableFuture
使用原生的CompletableFuture实现异步操作,加上对lambda的支持,可以说实现异步任务已经发挥到了极致。
@Test
public void test2() throws Exception {
System.out.println("main函数开始执行");
ExecutorService executor = Executors.newFixedThreadPool(2);
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
System.out.println("===task start===");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("===task finish===");
return 3;
}
}, executor);
future.thenAccept(e -> System.out.println(e));
System.out.println("main函数执行结束");
}
四、Spring的Async注解
使用spring实现异步需要开启注解,可以使用xml方式或者java config的方式。
xml方式: <task:annotation-driven />
<task:annotation-driven executor="executor" />
<task:executor id="executor"
pool-size="2" 线程池的大小
queue-capacity="100" 排队队列长度
keep-alive="120" 线程保活时间(单位秒)
rejection-policy="CALLER_RUNS" 对拒绝的任务处理策略 />
java方式:
@EnableAsync
public class MyConfig {
@Bean
public TaskExecutor executor(){
ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); //核心线程数
executor.setMaxPoolSize(20); //最大线程数
executor.setQueueCapacity(1000); //队列大小
executor.setKeepAliveSeconds(300); //线程最大空闲时间
executor.setThreadNamePrefix("fsx-Executor-"); //指定用于新创建的线程名称的前缀。
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
(1)@Async
@Test
public void test3() throws Exception {
System.out.println("main函数开始执行");
myService.longtime();
System.out.println("main函数执行结束");
}
@Async
public void longtime() {
System.out.println("我在执行一项耗时任务");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("完成");
}
(2)AsyncResult
如果需要返回值,耗时方法返回值用AsyncResult包装。
@Test
public void test4() throws Exception {
System.out.println("main函数开始执行");
Future<Integer> future=myService.longtime2();
System.out.println("main函数执行结束");
System.out.println("异步执行结果:"+future.get());
}
@Async
public Future<Integer> longtime2() {
System.out.println("我在执行一项耗时任务");
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("完成");
return new AsyncResult<>(3);
}
Java实现异步调用的更多相关文章
- 利用回调实现Java的异步调用
异步是指调用发出后,调用者不会立刻得到结果,而是在调用发出后,被调用者通知调用者,或通过回调函数处理这个调用. 回调简单地说就是B中有一个A,这样A在调用B的某个方法时实际上是调用到了自己的方法. 利 ...
- java实现异步调用实例
在JAVA平台,实现异步调用的角色有如下三个角色: 调用者 取货凭证 真实数据 一个调用者在调用耗时操作,不能立即返回数据时,先返回一个取货凭证.然后在过一断时间后凭取货凭证来获取真正的数据. ...
- Java 实现异步调用
首先 我遇到的问题是 接口调用时需要更新缓存 而更新缓存又是个说快不快的过程 所以打算做异步调用 返回我所需要的结果即可 ,至于缓存什么时候更新完 就不是我所需要关注的了 废话不多说 上代码 publ ...
- java中异步调用注意
Future接口是Java标准API的一部分,在java.util.concurrent包中.Future接口是Java线程Future模式的实现,可以来进行异步计算. 有了Future就可以进行三段 ...
- java中异步调用的解决方法
package demo.future; import java.util.ArrayList; import java.util.List; import java.util.concurrent. ...
- 5种必会的Java异步调用转同步的方法你会几种
转载请注明本文地址:https://www.jianshu.com/p/f00aa6f66281 源码地址:https://gitee.com/sunnymore/asyncToSync Sunny先 ...
- Java多线程实现异步调用
在Java平台,实现异步调用的角色有如下三个角色:调用者. 提货单 .真实数据,一个调用者在调用耗时操作,不能立即返回数据时,先返回一个提货单 .然后在过一断时间后凭提货单来获取真正的数据.去蛋糕店买 ...
- 从Java future 到 Guava ListenableFuture实现异步调用
从Java future 到 Guava ListenableFuture实现异步调用 置顶 2016年04月24日 09:11:14 皮斯特劳沃 阅读数:17570 标签: java异步调用线程非阻 ...
- java future模式 所线程实现异步调用(转载
java future模式 所线程实现异步调用(转载) 在多线程交互的中2,经常有一个线程需要得到另个一线程的计算结果,我们常用的是Future异步模式来加以解决.Future顾名思意,有点像期货市场 ...
随机推荐
- js 看图识国家
<!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"> ...
- Linux下C语言RPC(远程过程调用)编程实例
在查看libc6-dev软件包提供的工具(用 dpkg -L libc6-dev 命令)的时候,发现此软件包提供了一个有用的工具rpcgen命令.通过rpcgen的man手册看到此工具的作用是把RPC ...
- SQLServer 可更新订阅数据在线架构更改(增加字段)方案
原文:SQLServer 可更新订阅数据在线架构更改(增加字段)方案 之前一直查找冲突发布和订阅数据不一致的原因,后来发现多少数据库升级引起,因为一直以来都是在发布数据库增加字段,订阅也会自动同步.在 ...
- C#从列表中取元素的某个字段组成新的列表
using System; using System.Collections.Generic; using System.Linq; namespace CSharpDemo { class Prog ...
- SQL 时间格式化函数发布
SQL 时间格式化函数,有时候因某种需要需要格式化成需要的时间格式,需要的朋友可以收藏下,以备后用. SQL Server里面可能经常会用到的日期格式转换方法: sql server使用convert ...
- Arch Linux 是个 针对 i686 优化的 Linux 发行版(通过可以轻松使用的二进制包系统 - pacman)
Arch Linux 是个 针对 i686 优化的 Linux 发行版(通过可以轻松使用的二进制包系统 - pacman)Arch 同时也拥有一个类似 ports 的包构建系统(Arch Build ...
- 给变量赋值,程序会跳到 HardFault_Handler的问题
原因:变量属于指针,该指针没有初始化
- qtchooser - a wrapper used to select between Qt development binary(2种方法)
---------------------------------------------------------------------------------------------------- ...
- 测试 Components 与 Controls 的区别(嵌套在Panel上的Edit,依然是Form1的Component)
本例效果图: 代码文件: unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, ...
- Google地图下载工具代码
// // Google Map Tiles Downloader in C# by coolypf // No rights reserved, neither warranty nor guara ...