SpringBoot + 线程池 + 多线程

当项目中短时间内有大量的请求又追求性能时,可以考虑使用多线程来处理。现在Java都是推荐使用线程池来管理线程,不在显式创建线程了。

以下是示例代码:

因此创建一个线程池是必须的

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;


/**
 * 线程池配置
 * @author Zac
 */
@Configuration
@EnableAsync
public class TaskExecutorConfig {


    private static final Logger logger = LoggerFactory.getLogger(TaskExecutorConfig.class);

    @Bean
    public ThreadPoolTaskExecutor asyncServiceExecutor() {
        logger.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(10);
        //配置最大线程数
        executor.setMaxPoolSize(10);
        //配置队列大小
        executor.setQueueCapacity(10);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("thread-task-service-");
        //配置线程允许的空闲时间
        executor.setKeepAliveSeconds(60);
        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
//
//        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
//        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
//        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

异步多线程根据业务需求又分有有返回的和无返回的两种

一、无返回线程

无返回线程也是默认返回线程,既新开另一个线程去执行某个方法,然后当前线程跳过该方法继续往下执行

推荐使用@Async 注解方便快捷,括号内是指定加入的线程池,注意调用方与被调用的线程必须在不同的类上才能生效

注解方式

新建一个测试类futureTest.java,加入以下代码

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;


@Component
public class futrueTest {



    @Async("asyncServiceExecutor")
    public String asyncString(String i ){
System.out.println("异步线程:" + Thread.currentThread().getName() + "开始执行");

        try {

            Thread.sleep(1000 * 4);
        } catch (InterruptedException e) {
            return "error" + i;
        }
System.out.println("异步线程:" + Thread.currentThread().getName() + "执行完毕");
        return "success:" + i;

    }

}

测试接口


                
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值