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拋出的異常。