Springboot 学习之异步运行

一、简单实现

启动一个新的线程来运行

	Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 此处编写异步运行代码
            }
        });
	thread.start();

二、注解实现

1.先写一个异步配置类

@Configuration //表明该类是一个配置类
@EnableAsync //开启异步事件的支持
public class AsyncConfig {

    //此处成员变量应该使用@Value从配置中读取
    private int corePoolSize = 10; // 配置线程池中的核心线程数
    private int maxPoolSize = 200;  // 配置最大线程数
    private int queueCapacity = 10; // 配置队列大小

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }
}
2.在需要异步运行的方法或者类加上 @Async 注解
@Async
public class asyncTestClass{
	public void asyncTest() {
	 System.out.println("Execute method with configured executor - "
	 + Thread.currentThread().getName());
	}
}

@Async
public void asyncTest() {
 System.out.println("Execute method with configured executor - "
 + Thread.currentThread().getName());
}

调用被 @Async 标记的方法的调用者不能和被调用的方法在同一类中不然不会起作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值