Spring boot多线程支持

本文介绍如何在Spring框架中使用异步任务处理长时间运行的任务,通过配置系统线程池并结合@Controller和@Service注解实现web接口异步调用。

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

项目中经常会遇到一些执行时间较长的任务,这个时候很容易就想到使用多线程来处理。由于这个需求太常用,因此我们的spring大佬就直接帮我们从框架层面实现。

实例代码:web接口异步

MutiThreadApplication

@SpringBootApplication
@EnableAsync    //注意加这个注解,启动异步功能
public class MutiThreadApplication {

    //配置系统线程池
    @Bean
    public Executor getExecutor() {
        ThreadPoolTaskExecutor  executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(25);
        executor.setAwaitTerminationSeconds(20000);
        return executor;
    }

    public static void main(String[] args) {
        SpringApplication.run(MutiThreadApplication.class, args);
    }
}

TestController

package com.liao.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.liao.service.TestService;


@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("/test")
    public String test() {
        System.out.println("main:start");
        testService.test();

        System.out.println("main:end");

        return "end";
    }

}

TestService

package com.liao.service;

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

@Service
public class TestService {

    @Async  //此注解标识该方法要异步执行,spirng会启动一个线程异常执行该方法
    public void test() {
        System.out.println(Thread.currentThread().getName()+":start");

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName()+":end");
    }

}

执行结果
web请求立刻返回结果。
系统日志如下:

main:start
main:end
getExecutor-1:start
getExecutor-1:end
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值