SpringBoot @Async 异步处理注解实现

注解实现异步多线程非阻塞

文件结构:

在这里插入图片描述

环境jar包:

 jdk: jdk1.8.0_121(32位)
		pom:
			 <dependency>
	            <groupId>org.springframework</groupId>
	            <artifactId>spring-context</artifactId>
	            <version>5.0.10.RELEASE</version>
	        </dependency>

配置类 TaskExecutorConfig:

 package com.Async;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.Executor;
@Configuration
@EnableAsync //启用异步
@ComponentScan("com.Async")
public class TaskExecutorConfig implements AsyncConfigurer {//实现异步接口
	//异步线程池配置
    public Executor getAsyncExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(5);//常规线程数量
        threadPoolTaskExecutor.setMaxPoolSize(10);//最大线程数量
        threadPoolTaskExecutor.setQueueCapacity(100);//等待执行线程队列数量
        threadPoolTaskExecutor.initialize();//构建
        return threadPoolTaskExecutor;
    }
	
}

异步方法类 AsyncTaskService:

package com.Async;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncTaskService {
    @Async //注解异步方法
    public void execute(Integer i) {
        System.out.println("执行异步输出execute: "+i);
    }
    @Async
    public void executeAsyncTaskPlus(Integer i){
        System.out.println("执行异步输出executeAsyncTaskPlus: "+i);
    }
}


测试类Main:

package com.Async;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String  [] args){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
        AsyncTaskService bean = applicationContext.getBean(AsyncTaskService.class);
        for (int i = 0;i < 10; i++){
            bean.execute(i);
            bean.executeAsyncTaskPlus(i);
        }
        applicationContext.close();
    }
}

输出结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值