线程池:spring封装的ThreadPoolTaskExecutor-线程池应用

适用场景:

在要处理大批量无序 的数据 前提下,可使用下面方案,可提高线上服务器吞吐量。以下有场景以及推荐方案。

一、 ThreadPoolTaskExecutor应用demo

代码实现ThreadPoolTest

listRules=先检索有多少人开通了规则,轮训每个规则 调用线程池,开4个线程循环给这个用户投资
他的数据不满足条件才结束,比如余额低于他规则里设置的最低持有余额,则停止给他投资。

 
import java.math.BigDecimal;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import com.zkbc.core.exception.PlatformException;

public class ThreadPoolTest{
    private static Logger log = LoggerFactory.getLogger(ThreadUtilTest2.class);
    @Autowired
    private TaskExecutor tasktestExecutor;

    @Before
    public void init() {
        BeanFactoryUtil.init();
        tasktestExecutor = (TaskExecutor) BeanFactoryUtil.getContext().getBean("tasktestExecutor");
    }

    @Test
    public void autoTest() {
        log.info("step 1 :  自动跑批某个业务,通常会添加个业务开关,设置为可配置。");
        log.info("step 2 :  按条件,以及数据量要求检索要处理的数据  for循环 +线程池调用。");
        log.info("step 2.1 : 如果有不怎么变动的类似规则列表之类的数据,避免频繁查库,可以放到缓存读取。"
       +" 另一边规则无论是数量还是内容只要变动则把缓存中的规则map值删掉
       +" 使用规则前判断是否需要初始化map");
       
/** 开四个线程,1000次循环,如果有空闲线程则可以复用,会调用空闲线程,如没有,加入队列进行排队。*/
        for (int i = 1; i < 1000; i++) {//检索出来的条数
            try {
                tasktestExecutor.execute(new AutoInvest4Original(new BigDecimal("" + i)));
            } catch (Exception e) {
                log.info("xxxxx异常", e);
            }
        }
    }

    public class AutoInvest4Original implements Runnable {
        private BigDecimal air;//你要处理的业务对象

        public AutoInvest4Original(BigDecimal air) {
            super();
            this.air = air;
        }

        @Override
        public void run() {
            Thread current = Thread.currentThread();
            log.info("timeStamp:" + DateUtil.formatToYYYY_MM_DDHHMMSS(new Date()) + ",第" + air + "个  ,   current.getId="
                    + current.getId() + ",current.hashCode=" + current.hashCode());
          
            /* 关于线程可以打印很多信息  ,如:"current.getPriority=" + current.getPriority() + ",current.getName=" + current.getName()
            + ",current.activeCount=" + current.activeCount() + ",current.getId=" + current.getId()
            + ",current.getThreadGroup=" + current.getThreadGroup() + ",current.getStackTrace="
            + current.getStackTrace() + ",current.hashCode=" + current.hashCode() + ",current.toString="
            + current.toString() */
         
            log.info("step 3 :  调用要处理数据的代码块,最好加上一段try{} catch(){} ");
            /*for ....:
                try {
                //eg:该用户投资某个标的,先可用户可投资金额投完才能轮到下个用户,但是标的存在  每次限投限制,
                //还有该用户最多投资限制,每份金额以及最小投资金额.act
                investingByUserRule(air);
                } catch (PlatformException e) {
                    log.info("用户【" + air + "】投资异常", e);
                }
             */

        }
    }

    /**while循环里用户没钱了,或者用户对于该标的投资完已经不满足继续投资该标的资格,则退出,如果用户还有钱则购买下个标的*/
    private void investingByUserRule(BigDecimal air) throws PlatformException {
        while (true) {
            log.info("step 4 :处理每条数据之前,都要检查下该数据是否已经不满足处理条件或者已经被修改,则continue ");
            log.info("step 5 :check要处理的数据entry ,没有 则放弃处理,直接break.");
            /**if(!ishaveEntry){
            * break;
            * }
            * */
        }

    }

}

spring注册bean的配置文件添加如下配置:

 applicationcontext.xml
    	<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="4"/> -- 核心线程数
        <property name="maxPoolSize" value="4"/> -- 线程池中最大线程数
        <property name="queueCapacity" value="3000"/> -- 队列容量
        <property name="keepAliveSeconds" value="3000"/>-- 空闲线程存活时间,即超过核心线程数的线程,在多长时间内,会被销毁
        <property name="waitForTasksToCompleteOnShutdown" value="true"/>-- 线程池使用完要关闭,关闭线程池采用等待线程执行完才关闭(shutdown)而非立即关闭(shutdownnow)
        <property name="rejectedExecutionHandler">
        	<bean class="java.util.concurrent.ThreadPoolExecutor$AbortPolicy" />   -- 拒绝策略通常 采用的是丢弃抛异常的
        </property>
    </bean>

二、观察测试结果

以下一段比较明显,可以看出同一时间会有多个线程并行执行,大大提高服务器效率,也能够看出线程抢占cpu的无序性。

timeStamp:2018-05-30 16:55:29,第979个  ,   current.getId=85,current.hashCode=2056950446 
timeStamp:2018-05-30 16:55:29,第984个  ,   current.getId=88,current.hashCode=1308138298 
timeStamp:2018-05-30 16:55:29,第983个  ,   current.getId=87,current.hashCode=383362271  
timeStamp:2018-05-30 16:55:29,第982个  ,   current.getId=86,current.hashCode=291955534  
timeStamp:2018-05-30 16:55:29,第987个  ,   current.getId=87,current.hashCode=383362271  
timeStamp:2018-05-30 16:55:29,第986个  ,   current.getId=88,current.hashCode=1308138298 
timeStamp:2018-05-30 16:55:29,第985个  ,   current.getId=85,current.hashCode=2056950446 
timeStamp:2018-05-30 16:55:29,第990个  ,   current.getId=88,current.hashCode=1308138298 
timeStamp:2018-05-30 16:55:29,第989个  ,   current.getId=87,current.hashCode=383362271  
timeStamp:2018-05-30 16:55:29,第988个  ,   current.getId=86,current.hashCode=291955534  
timeStamp:2018-05-30 16:55:29,第993个  ,   current.getId=87,current.hashCode=383362271  
timeStamp:2018-05-30 16:55:29,第992个  ,   current.getId=88,current.hashCode=1308138298 
timeStamp:2018-05-30 16:55:29,第991个  ,   current.getId=85,current.hashCode=2056950446 
timeStamp:2018-05-30 16:55:29,第996个  ,   current.getId=88,current.hashCode=1308138298 
timeStamp:2018-05-30 16:55:29,第995个  ,   current.getId=87,current.hashCode=383362271  
timeStamp:2018-05-30 16:55:29,第994个  ,   current.getId=86,current.hashCode=291955534  
timeStamp:2018-05-30 16:55:29,第999个  ,   current.getId=87,current.hashCode=383362271  
timeStamp:2018-05-30 16:55:29,第998个  ,   current.getId=88,current.hashCode=1308138298 
timeStamp:2018-05-30 16:55:29,第997个  ,   current.getId=85,current.hashCode=2056950446 

三、 spring的线程池ThreadPoolTaskExecutor部分源码阅读

1、关于线程池【ThreadPoolTaskExecutor】的设置,查阅局部源码
  • corePoolSize 指定线程池中的线程数量
  • maxPoolSize 即为jdk中的maximumPoolSize ,即制定了线程池中的最大线程数量。
  • keepAliveSeconds :线程池中线程数量超过corePoolSize 的时候,多余的空闲线程会在这个设定的时间段内被销毁。
    在这里插入图片描述
  • 队列大小
    队列大小定义为 int 类型,则容量是integer最大值。观看源码能看到 赋队列默认初始值即为 Integer.MAX_VALUE; 所以一般我们使用的时候会给队列设置一个初始值。
/**
	 * Set the capacity for the ThreadPoolExecutor's BlockingQueue.
	 * Default is {@code Integer.MAX_VALUE}.
	 * <p>Any positive value will lead to a LinkedBlockingQueue instance;
	 * any other value will lead to a SynchronousQueue instance.
	 * @see java.util.concurrent.LinkedBlockingQueue
	 * @see java.util.concurrent.SynchronousQueue
	 */
	public void setQueueCapacity(int queueCapacity) {
		this.queueCapacity = queueCapacity;
	}
	

都看到这了,那我想知道他用的是啥队列啊?
线程池调度器使用的是spring封装的:ThreadPoolTaskExecutor,内部使用的队列是: 队列容量大于0则使用 LinkedBlockingQueue队列,否则使用 SynchronousQueue队列;

参看短文:LinkedBlockingQueue 和 SynchronousQueue 究竟都是怎么回事?在这里插入图片描述
– rejectedExecutionHandler 拒绝策略
参看短文:线程池中的拒绝策略

2、使用spring封装的线程池ThreadPoolTaskExecutor缺点

不能指定线程名称,出现问题不好追溯。

如果出现问题,不能直观的知道是哪个线程出的问题,因为封装 ThreadPoolExecutor 的时候,线程工厂使用默认的而没有自定义,这样就不能指定创建的线程名称,排查问题的时候比较难搞。

通过自定义线程工厂 ThreadFactory ,可以指定线程的名称,原因是线程池 是通过 线程工厂 ThreadFactory 来创建线程的,看如下源码可知,线程工厂 ThreadFactory 只有创建线程这一个方法
在这里插入图片描述
建议:
在线程池自定义线程工厂的时候可以统一指定线程名称【而且阿里规约里也有提到使用线程池的时候,建议自定义线程工厂,出问题时方便溯源】 如何指定创建线程的名称呢?
代码实现:

private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("center-pool-%d").build();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值