@EnableAsync@Async 使用详解

我们在使用多线程的时候,往往需要创建Thread类,或者实现Runnable接口,如果要使用到线程池,我们还需要来创建Executors,在使用spring中,已经给我们做了很好的支持。只要要@EnableAsync就可以使用多线程。使用@Async就可以定义一个线程任务。通过spring给我们提供的ThreadPoolTaskExecutor就可以使用线程池。

默认情况下,Spring将搜索相关的线程池定义:要么在上下文中搜索唯一的TaskExecutor bean,要么搜索名为“taskExecutor”的Executor bean。如果两者都无法解析,则将使用SimpleAsyncTaskExecutor来处理异步方法调用。

@SpringBootApplication
@ServletComponentScan
@EnableAsync
public class AmpicApplication {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext run = SpringApplication.run(AmpicApplication.class, args);

        AccountBookService accountBookService=(AccountBookService)run.getBean("accountBookService");

        accountBookService.getStatus();
        accountBookService.getStatus2();

    }

    private static final int corePoolSize = 10;       		// 核心线程数(默认线程数)
    private static final int maxPoolSize = 100;			    // 最大线程数
    private static final int keepAliveTime = 10;			// 允许线程空闲时间(单位:默认为秒)
    private static final int queueCapacity = 200;			// 缓冲队列数
    private static final String threadNamePrefix = "Async-Service-"; // 线程池名前缀

    @Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
    public ThreadPoolTaskExecutor getAsyncExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix(threadNamePrefix);

        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }


}

 @Async(value = "taskExecutor")
    public void getStatus() throws Exception {
        System.out.println("开始了");
        List list = new ArrayList();
        list.add(1);
        list.forEach((a) -> {
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println(i);
                }
            } catch (Exception e) {
            }
        });
        System.out.println("结束了");
    }
    @Async(value = "taskExecutor")
    public void getStatus2() throws Exception {
        System.out.println("开始了2");
        List list = new ArrayList();
        list.add(1);
        list.forEach((a) -> {
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println(i);
                }
            } catch (Exception e) {
            }
        });
        System.out.println("结束了2");
    }

运行结果:::

开始了
开始了2
0
1
2
3
4
5
6
7
8
9
结束了
0
1
2
3
4
5
6
7
8
9
结束了2

通过运行结果可以看出来 第二个方法并没有在第一个方法结束之后才调用,而是在第一个方法运行过程中就执行了第二个方法.实现了多线程异步运行 .

使用这个是需要注意的地方:
一、异步方法使用static修饰
二、异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
三、异步方法不能与异步方法在同一个类中
四、类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
五、如果使用SpringBoot框架必须在启动类中增加@EnableAsync注解
六、在Async 方法上标注@Transactional是没用的。 在Async 方法调用的方法上标注@Transactional 有效。
七、调用被@Async标记的方法的调用者不能和被调用的方法在同一类中不然不会起作用
八、使用@Async时要求是不能有返回值的不然会报错的 因为异步要求是不关心结果的

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值