@Async如何使用

本文介绍了在Spring Boot中使用@Async进行异步方法调用的详细步骤,包括启动类添加@EnableAsync,方法和类添加注解,以及自定义线程池的配置。通过测试展示了SimpleAsyncTaskExecutor默认行为和自定义线程池的区别,强调了合理配置线程池参数的重要性。
摘要由CSDN通过智能技术生成

@Async注解

我们都知道使用@Async标注在方法上,可以使该方法异步的调用执行。而所有异步方法的实际执行是交给TaskExecutor的。

关于@Async的基本知识不做讲解,只是对于使用过程中需要的注意的点做下强调。

最简单的使用

1.启动类添加@EnableAsync注解

package com.lara.springbootconfig;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * @author lara
 */
@SpringBootApplication
@EnableAsync
public class SpringBootConfigApplication {
   

    public static void main(String[] args) {
   
        SpringApplication.run(SpringBootConfigApplication.class, args);
    }
}

2. 方法上添加@Async,类上添加@Component

package com.lara.springbootconfig.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.Future;

/**
 * @author lara
 */
@Component
@Slf4j
public class SyncTask {
   
    public static Random random =new Random();

    @Async
    public Future<String> doTaskOne() throws Exception {
   
        String threadName = Thread.currentThread().
  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值