欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用spring的@Async异步执行方法

程序员文章站 2022-07-15 14:56:35
...

应用场景:

1、某些耗时较长的而用户不需要等待该方法的处理结果

2、某些耗时较长的方法,后面的程序不需要用到这个方法的处理结果时


在spring的配置文件中加入对异步执行的支持

    <!-- 支持异步方法执行 -->
    <task:annotation-driven />

使用方法

import org.springframework.scheduling.annotation.Async;

public class Test {
    
    @Async
    public static void testAsyncMethod(){
        try {
            //让程序暂停100秒,模拟执行一个很耗时的任务
            Thread.sleep(100000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

调用方法

public static void main(String[] args) {
    Test.testAsyncMethod();
    System.out.println("我已经执行了!");
}





转载于:https://my.oschina.net/jgy/blog/550673