SpringBoot 多线程

本文介绍如何在Spring框架中使用线程池和异步处理来提高应用程序的并发能力和响应速度。通过创建配置类并定义线程池参数,我们可以轻松地实现任务的异步执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程池:线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。如果某个线程在托管代码中空闲(如正在等待某个事件),则线程池将插入另一个辅助线程来使所有处理器保持繁忙。如果所有线程池线程都始终保持繁忙,但队列中包含挂起的工作,则线程池将在一段时间后创建另一个辅助线程但线程的数目永远不会超过最大值。超过最大值的线程可以排队,但他们要等到其他线程完成后才启动。

异步处理:一个可以无需等待被调用函数的返回值就让操作继续进行的方法

异步调用,提供了一种非阻塞形式的方法调用,在无需立即得到返回值的场景下,有助于提高系统的并发能力.

一、创建ThreadConfig类,注意,需标记@EnableAsyn

a.配置类方法1

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
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 java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration // 声明当前类是一个配置类,相当于Spring配置的XML文件
@ComponentScan(basePackages={"com.exception"})
@EnableAsync// 利用@EnableAsync注解开启异步任务的支持
// 配置类实现AsyncConfigurer接口并重写getAsyncExecutor方法,并返回ThreadPoolTaskExecutor,
这样我们就获得了一个基于线程池TaskExecutor
public class ThreadConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        taskExecutor.setCorePoolSize(5);
        // 最大线程数
        taskExecutor.setMaxPoolSize(50);
        // 队列最大长度
        taskExecutor.setQueueCapacity(1000);
        // 线程池维护线程所允许的空闲时间(单位秒)
        taskExecutor.setKeepAliveSeconds(120);
        // 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,
调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        taskExecutor.initialize();
        return taskExecutor;
    }

    @Bean
    public Executor getThreadPool() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(1000);
        taskExecutor.setQueueCapacity(1000);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }

}

b.配置类方法2

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration // 声明当前类是一个配置类,相当于Spring配置的XML文件
@ComponentScan(basePackages={"com.exception"})
@EnableAsync// 利用@EnableAsync注解开启异步任务的支持
// 配置类实现AsyncConfigurer接口并重写getAsyncExecutor方法,并返回ThreadPoolTaskExecutor,这样我们就获得了一个基于线程池TaskExecutor
public class ThreadConfig {

    @Bean
    public Executor getThreadPool() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(1000);
        taskExecutor.setQueueCapacity(1000);
        taskExecutor.initialize();
        return taskExecutor;
    }


}

二、编写异步测试方法,注意,需标记@Async

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

import javax.annotation.Resource;
import java.util.concurrent.Executor;

/**
 * 多线程的测试类
 */
@Service
public class AsynTaskService{

    @Resource(name = "getThreadPool")
    private Executor executor;

    @Async
    // 通过@Async注解方法表明这个方法是一个异步方法,如果注解在类级别,则表名该类的所有方法都是异步的,
    // 而这里的方法自动被注入使用ThreadPoolTaskExecutor作为TaskExecutor
    public void executeAsyncTask(Integer i) {
        System.out.println("执行异步任务:" + i);
    }

    public void executeAsyncTaskPlus(Integer i) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行异步任务+1:" + i);
            }
        });
    }
}

二、测试方法

import com.lenovo.pcsd.bp.businesspartner.exception.AsynTaskService;
import org.junit.After;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by yuhao.wang on 2017/3/9.
 */
public class TestMain{
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ThreadConfig.class);

    @Test
    public void contextTest() {
        AsynTaskService demoThreadService = context.getBean(AsynTaskService.class);
        for (int i = 0; i < 30; i++) {

            demoThreadService.executeAsyncTaskPlus(i);
            demoThreadService.executeAsyncTask(i);
        }
    }

    @After
    public void closeContext() {
        context.close();
    }

}

结果

uu+1:0
执行异步任务:0
uu+1:1
执行异步任务:1
执行异步任务:2
uu+1:2
执行异步任务:3
uu+1:5
执行异步任务:7
uu+1:7
执行异步任务:6
执行异步任务:10
执行异步任务:11
执行异步任务:12



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

javafanwk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值