spring 异步处理@Async

最近刚要用到异步处理小结一下:

异步执行:所谓异步,就是当执行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!");
        }
}

结果:
这里写图片描述

稍后会做细致分析……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值