线程池xml配置的方式.txt

xml中配置:
<bean id="threadPoolTaskExecutor" name="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <!-- 核心线程数 线程池维护线程的最少数量 -->
        <property name="corePoolSize" value="10" />
        <!-- 线程池维护线程所允许的空闲时间 -->
        <property name="keepAliveSeconds" value="200" />
        <!-- 线程池维护线程的最大数量 -->
        <property name="maxPoolSize" value="50" />
        <!-- 线程池所使用的缓冲队列 -->
        <property name="queueCapacity" value="1000" />
        <!-- 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.  -->
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
        </property>
    </bean>

    <bean id="scheduledExecutorService" name="scheduledExecutorService" class="org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean">
        <!-- 核心线程数 线程池维护线程的最少数量 延迟任务不会丢失,只会延后执行导致延迟时间不够准确-->
        <property name="poolSize" value="5" />
        <!--此处的任务拒绝策略意义不大,因为此线程次的任务队列是无边界的,故只有在整个线程池在非running情况下才会执行该策略-->
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
        </property>
    </bean>
    
在代码中使用:
    装配对象:
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    
    具体代码:
    threadPoolTaskExecutor.execute(new SendTrainPushMessageThread(messageMap));
    
    threadPoolTaskExecutor为一般线程池
    scheduledExecutorService为延迟线程池
    
    
countDownLatch使用:
主线程中:
CountDownLatch begin = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(2);
--excute需要的几个线程
begin.countDown();    减一(计数器实现)
end.await();        等待,直到该计数器为0时,继续执行
其他线程中:
begin.await();
System.out.println("do someThing");
end.countDown()

submit和excute的区别
1、接收的参数不一样
2、submit有返回值,而execute没有
Method submit extends base method Executor.execute by creating and returning a Future that can be used to cancel execution and/or wait for completion. 
用到返回值的例子,比如说我有很多个做validation的task,我希望所有的task执行完,然后每个task告诉我它的执行结果,是成功还是失败,如果是失败,原因是什么。然后我就可以把所有失败的原因综合起来发给调用者。
个人觉得cancel execution这个用处不大,很少有需要去取消执行的。
而最大的用处应该是第二点。
3、submit方便Exception处理
如果你在你的task里会抛出checked或者unchecked exception,而你又希望外面的调用者能够感知这些exception并做出及时的处理,那么就需要用到submit,通过捕获Future.get抛出的异常。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章