springboot主线程_Spring Boot实践——多线程

本文介绍了Spring Boot中实现多线程的两种方式:一是通过TaskExecutor和ThreadPoolTaskExecutor配置异步任务;二是直接使用Java的ThreadPoolExecutor创建线程调度管理器。详细展示了配置类、任务创建及触发任务的代码示例。
摘要由CSDN通过智能技术生成

多线程

Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程。使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。而实际开发中任务一般是非阻碍的,即异步的,所以我们要在配置类中通过@EnableAsync开启对异步任务的支持,并通过在实际执行的Bean的方法中使用@Async注解声明其是一个异步任务。

此外,还提供一种Java的实现方式,多种方式去尝试如何去实现多线程。

实现

一、基于Spring

1、配置类

importjava.util.concurrent.Executor;importorg.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;importorg.springframework.scheduling.annotation.AsyncConfigurer;importorg.springframework.scheduling.annotation.EnableAsync;importorg.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;/*** @Description: 配置类实现AsyncConfigurer接口,并重写getAsyncExecutor方法,并返回一个ThreadPoolTaskExecutor,

* 这样我们就获得一个基于线程池TaskExecutor

* @ClassName: CustomMultiThreadingConfig

* @Author: OnlyMate

* @Date: 2018年9月21日 下午2:50:14*/@Configuration

@ComponentScan("com.only.mate.springboot.multithreading")

@EnableAsync//利用@EnableAsync注解开启异步任务支持

public class CustomMultiThreadingConfig implementsAsyncConfigurer{

@OverridepublicExecutor getAsyncExecutor() {

ThreadPoolTaskExecutor taskExecutor= newThreadPoolTaskExecutor();

taskExecutor.setCorePoolSize(5);

taskExecutor.setMaxPoolSize(10);

taskExecutor.setQueueCapacity(25);

taskExecutor.initialize();returntaskExecutor;

}

@OverridepublicAsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();

}

}

2、创建线程任务

importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.scheduling.annot

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值