springboot 线程池学习

springboot 线程池学习


本人的第一篇博客,主要用来备忘及督促自己学习。

最近闲下来看了springboot 线程池的使用,也许今后会用到。
定义线程池

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@SpringBootApplication
public class MyspringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyspringbootApplication.class, args);
    }
    @EnableAsync
    @Configuration
    class TaskPoolConfig {

        /**
         * 核心线程数10:线程池创建时候初始化的线程数
         * 最大线程数20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
         * 缓冲队列200:用来缓冲执行任务的队列
         * 允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
         * 线程池名的前缀:线程名称前缀,方便我们查找区分  myTaskPool-1、myTaskPool-2  这样
         * 线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
         */
        @Bean("myTaskPool")
        public Executor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(10);
            executor.setMaxPoolSize(20);
            executor.setQueueCapacity(200);
            executor.setKeepAliveSeconds(60);
            executor.setThreadNamePrefix("myTaskPool-");
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            return executor;
        }
    }

然后是使用:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.Future;

/**
 * @Auther: Administrator
 * @Date: 2018/11/5 14:39
 * @Description:
 */
@Component
public class TestTask {
    public static Random random = new Random();
    Logger logger = LoggerFactory.getLogger(getClass());
    @Async("myTaskPool")
    public Future<String> doTaskOne() throws Exception {
        logger.info("开始做任务一");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        logger.info("完成任务一,耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>("任务一完成");
    }

    @Async("myTaskPool")
    public Future<String> doTaskTwo() throws Exception {
        logger.info("开始做任务二");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        logger.info("完成任务二,耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>("任务二完成");
    }

    @Async("myTaskPool")
    public Future<String> doTaskThree() throws Exception {
        logger.info("开始做任务三");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        logger.info("完成任务三,耗时:" + (end - start) + "毫秒");
        return new AsyncResult<>("任务三完成");
    }

通过异步注解@Async 使用线程池,需要写入线程池的名字,然后运行:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.Future;

/**
 * @Auther: Administrator
 * @Date: 2018/11/5 14:44
 * @Description:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {
    @Autowired
    private TestTask task;

    @Test
    public void test() throws Exception {

        Future<String> task1 = task.doTaskOne();
        Future<String> task2 = task.doTaskTwo();
        Future<String> task3 = task.doTaskThree();
        while(true) {
            if(task1.isDone() && task2.isDone() && task3.isDone()) {
                // 三个任务都调用完成,退出循环等待
                break;
            }
            Thread.sleep(1000);
        }
        //等待子线程结束
//        Thread.currentThread().join();
        System.out.println("子线程执行完毕");
    }

Future对象获取线程的结果,不然主线程会开启完线程后直接退出,日志什么都看不到
下面是执行结果
在这里插入图片描述

更新:
真的用到,同时用CompletableFuture对象小小的升级了一下,jdk要求最低1.8。
公司有个并发请求相同接口的需求,服务A通过feign传过来一个数组名单,其中每一个名字都要通过相同接口拿到一个返回值。遍历就太慢了,名单最多会有20+,其中myApi.getPrice(name,typeCode) 需要被多线程并发,只是一个普通的请求就不展开了,具体实现如下:

public RetEntity<List<MaintainInfoDTO>> getMaintain(@RequestParam("typecode") String typeCode, @RequestParam("partnames") String[] partNames) throws Exception {
        RetEntity<List<MaintainInfoDTO>> ret = new RetEntity<>();
        List<String> nameList = Arrays.asList(partNames).stream().filter(a->CommonUtil.isNotEmpty(a)&&!a.equals("null")).collect(toList());

        Executor executor = Executors.newFixedThreadPool(Math.min(nameList.size(), 20),//执行器个数,和需请求次数相同。最大20
            new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    //使用守护线程,使用这种方式不会组织程序的关停
                    thread.setDaemon(true);
                    return thread;
                }
            }
        );
        List<CompletableFuture<MaintainInfoDTO>> futures = nameList.stream()
            .map(a -> CompletableFuture.supplyAsync(()->myApi.getPrice(a,typeCode),executor)).collect(toList());
		//上面是调用和拿到开始执行对象的list,其实并没有执行完毕
        List<MaintainInfoDTO> list = futures.stream()
            .map(CompletableFuture::join)
            .collect(toList());
            //这里就是已完成并取出返回值的list了
        ret.initRetList(list);
        return ret;
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值