spring 异步处理@Async
来源:互联网 发布:java抓取html指定内容 编辑:程序博客网 时间:2024/06/05 02:49
最近刚要用到异步处理小结一下:
异步执行:所谓异步,就是当执行A方法的过程中调用B方法,但是B方法并不影响A方法的执行效率,即使B方法没有执行结束还是会正常执行A方法。简单说异步执行就是先返回结果,再执行过程(或者 当执行A方法的过程中,只用满足某个条件是才会执行B方法,但是B方法的成功和失败并不影响A方法继续执行也就是说B方法和A方法的后续执行没有关系)
顺序执行:当执行A方法的过程当中调用B方法,只用B方法执行结束后才会继续执行A方法下面的代码,这就是平时写代码时用的方式
对比以上两种执行就不难理解什么是异步了
回到正题:Spring 中 @Async 注解
以下是一个简单的Demo:
需要在applicationContext.xml 中配置
<!--扫描注解 --> <context:component-scan base-package="com.mqsyoung" /> <context:annotation-config /> <!-- 支持异步方法执行 --> <task:annotation-driven />
one 异步方法:
@Component // 作用:告诉spring 此类是一个组件,让其扫描到public class AsyTest { @Async // 必须有次注解 public void sayHello3() throws InterruptedException { Thread.sleep(2 * 1000);//网络连接中 。。。消息发送中。。。 System.out.println("我爱你啊!"); }}
two 异步方法:
@Componentpublic class AsyTest2 { @Async public void test02() throws InterruptedException{ Thread.sleep(1000); System.out.println("好了,不要无理取闹了……"); for(int i=0;i<5;i++){ Thread.sleep(3000); System.out.println("好了,不要无理取闹了……"); } }}
测试类:
@RunWith(SpringJUnit4ClassRunner.class) //让测试时能够运行在Spring环境中@ContextConfiguration({"classpath:/config/applicationContext.xml"}) // 加载配置文件public class TestSpringAsync { @Autowired private AsyTest asyTest; @Autowired private AsyTest2 asyTest2; @Test public void test() throws InterruptedException, ExecutionException { asyTest2.test02(); System.out.println("你不爱我了么?"); asyTest.sayHello3(); Thread.sleep(1 * 1000);// 不让主进程过早结束 System.out.println("你竟无话可说, 我们分手吧。。。"); TestSpringAsync.sayHello1(); Thread.sleep(10 * 1000);// 不让主进程过早结束 } @Async public static void sayHello1() throws InterruptedException { // Thread.sleep(2 * 1000);//网络连接中 。。。消息发送中。。。 System.out.println("我爱你啊!!!1!"); }}
结果:
稍后会做细致分析……
阅读全文
0 0
- spring 异步处理@Async
- spring boot 集成Async 注解 异步处理
- Spring中的@Async注解 异步任务处理
- Spring中异步处理@Async注解
- Spring异步任务处理,@Async的配置和使用
- spring中使用@Async注解进行异步处理
- Spring异步任务处理,@Async的配置和使用
- spring中使用@Async注解进行异步处理
- Spring异步任务处理,@Async的配置和使用
- async模块的异步处理
- spring @Async 注解异步执行
- spring 配置异步要点 @Async
- Spring异步方法注解@Async
- spring 配置异步要点 @Async
- spring boot(17)-@Async异步
- spring boot(17)-@Async异步
- Spring boot 使用异步@Async
- Spring实现Async异步接口
- GET和POST的区别
- [6-04]spring面试题
- dwg转dxf使用迅捷CAd转换器转换
- Prime,Kruskal,Dijkstra算法
- 线程同步、死锁原理
- spring 异步处理@Async
- 38
- IDEA导入eclipse项目servlet运行404
- 张正友标定法-MATLAB实验
- 小程序文档整理之-- ajax请求
- MyEclipse WebSphere开发教程:安装和更新WebSphere 6.1, JAX-WS, EJB 3.0(一)
- 线程同步的解决办法
- 学生管理系统(七)---优化
- 普元 EOS Platform 7.5 如何把DataObject数组元素的值赋值给Criteria作为查询条件