最近刚要用到异步处理小结一下:
异步执行:所谓异步,就是当执行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 异步方法:
@Component
public 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!");
}
}
结果:
稍后会做细致分析……