一、创建线程

 @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实现异步调用的更多相关文章

  1. 利用回调实现Java的异步调用

    异步是指调用发出后,调用者不会立刻得到结果,而是在调用发出后,被调用者通知调用者,或通过回调函数处理这个调用. 回调简单地说就是B中有一个A,这样A在调用B的某个方法时实际上是调用到了自己的方法. 利 ...

  2. java实现异步调用实例

    在JAVA平台,实现异步调用的角色有如下三个角色: 调用者 取货凭证   真实数据 一个调用者在调用耗时操作,不能立即返回数据时,先返回一个取货凭证.然后在过一断时间后凭取货凭证来获取真正的数据.  ...

  3. Java 实现异步调用

    首先 我遇到的问题是 接口调用时需要更新缓存 而更新缓存又是个说快不快的过程 所以打算做异步调用 返回我所需要的结果即可 ,至于缓存什么时候更新完 就不是我所需要关注的了 废话不多说 上代码 publ ...

  4. java中异步调用注意

    Future接口是Java标准API的一部分,在java.util.concurrent包中.Future接口是Java线程Future模式的实现,可以来进行异步计算. 有了Future就可以进行三段 ...

  5. java中异步调用的解决方法

    package demo.future; import java.util.ArrayList; import java.util.List; import java.util.concurrent. ...

  6. 5种必会的Java异步调用转同步的方法你会几种

    转载请注明本文地址:https://www.jianshu.com/p/f00aa6f66281 源码地址:https://gitee.com/sunnymore/asyncToSync Sunny先 ...

  7. Java多线程实现异步调用

    在Java平台,实现异步调用的角色有如下三个角色:调用者. 提货单 .真实数据,一个调用者在调用耗时操作,不能立即返回数据时,先返回一个提货单 .然后在过一断时间后凭提货单来获取真正的数据.去蛋糕店买 ...

  8. 从Java future 到 Guava ListenableFuture实现异步调用

    从Java future 到 Guava ListenableFuture实现异步调用 置顶 2016年04月24日 09:11:14 皮斯特劳沃 阅读数:17570 标签: java异步调用线程非阻 ...

  9. java future模式 所线程实现异步调用(转载

    java future模式 所线程实现异步调用(转载) 在多线程交互的中2,经常有一个线程需要得到另个一线程的计算结果,我们常用的是Future异步模式来加以解决.Future顾名思意,有点像期货市场 ...

随机推荐

  1. 宽字符std::wstring的长度和大小问题?sizeof(std::wstring)是固定的32,说明std::wstring是一个普通的C++类,而且和Delphi不一样,没有负方向,因为那个需要编译器的支持

    std::wstring ws=L"kkkk";    int il=ws.length();    int ia=sizeof(ws);    int ib=sizeof(&qu ...

  2. Qt PNG 背景透明

    本文主要是解决Qt中QGraphicsAbstractShapeItem,QPixmap,QPainter等组件的透明化显示问题. 在Qt中定义了一个常量,用于设置透明的颜色,即Qt::transpa ...

  3. 使用Advanced Installer 13.1打包发布 Windows Service服务程序

    原文: 使用Advanced Installer 13.1打包发布 Windows Service服务程序 项目中需要用到一个定时推送案件状态的需求,本人小菜一只,在同事建议下要写成一个windows ...

  4. C# mysql set和enum属性字段的读取和添加

    1.使用Navicat for Mysql设置set和enum属性字段: a.enum类型 b.set类型 enum类型在创建表时需要设置初始值,在如图所示的位置设置. 2.C#读取和添加数据 a.e ...

  5. delphi Stomp客户端连接 RabbitMQ(1)

    最近公司想上个消息推送系统,网上搜了很多,因公司主要产品是Delphi,我选择了开源的RabbitMQ,Erlang语言开发,天生并行. 代码下载地址:delphistomp下载地址 windows上 ...

  6. MFC OnPaint()函数中最先调用CDialog::OnPaint()和最后调用CDialog::OnPaint()的巨大区别

    OnPaint()函数中最先调用CDialog::OnPaint()和最后调用CDialog::OnPaint()的巨大区别,如果没有注意这个问题就会出现无厘头式的绘图问题-- 效果就是出不来!在经过 ...

  7. Qt4.7.4下单独编译QtWebkit

    最近编译出了Qt4.7.4的嵌入式版本,但没有编译QtWebkit库.在编译一个使用Webkit的工程时出错,而根据工程的需要,要单独编译QtWebkit库.    由于不想再次编译整个的Qt库,于是 ...

  8. hive表批处理

    对hive中的表进行批量处理,如下是一个简单的脚本 #给定一个hive数据库名,生成它的所有表的create SQL语句,并导出到文件 create_fun(){ hive -e } #显示一个表中所 ...

  9. python读取json文件并解析

    # -*- coding: utf-8 -*- import os import json import sys reload(sys) sys.setdefaultencoding('utf-8') ...

  10. awk数组统计

    处理以下文件内容,将域名取出并根据域名进行计数排序处理:(百度和sohu面试题) http://www.etiantian.org/index.html http://www.etiantian.or ...