spring boot 多线程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/github_38151745/article/details/79224873

spring boot 通过任务执行器 taskexecutor 来实现多线程和并发编程。 使用threadpooltaskExecutor 可实现一个基于线程池的taskexecutor

spring boot 要实现多线程 首先需要创建一个配置类

@Configuration
@EnableAsync   //开启异步任务支持
public class SpringTaskExecutor implements AsyncConfigurer{  //实现AsyncConfigurer接口,重写getAsyncExecutor方法,返回一个基于线程池的taskExecutor

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(20);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}

接下来进行任务实现类的编写
通过该注解表明该方法是一个异步方法,这里的方法会自动被注入使用 thread pool task

@Service
public class AsyncTaskService {
    @Async  //通过该注解表明该方法是一个一部方法,这里的方法会自动被注入使用 thread  pool task executor  作为 task executor
    public void executorTaskOne(int i){
        System.out.println("执行异步任务:"+i);
    }
    @Async
    public void executorTaskTwo(int i) {
        System.out.println("执行异步任务+1:"+(i+1));
    }
}

在spring boot启动类中获取 实现类,调用方法。 当然在实际开发中可以直接使用@Autoaware注解调用,不需要在main方法中来调用,这里只是用来测试

ConfigurableApplicationContext context=SpringApplication.run(Application.class, args);
AsyncTaskService asyncTaskService =context.getBean(AsyncTaskService.class);
		for (int i=0;i<10;i++){
			asyncTaskService.executorTaskOne(i);
			asyncTaskService.executorTaskTwo(i);
		}

猜你喜欢

转载自blog.csdn.net/github_38151745/article/details/79224873