原來以為tiger已經(jīng)自帶了這種線程池,就是在任務(wù)數(shù)量超出時(shí)能夠阻塞住投放任務(wù)的線程,主要想用在JMS消息監(jiān)聽。
開始做法:
在ThreadPoolExcecutor中代入new ArrayBlockingQueue(MAX_TASK). 在任務(wù)超出時(shí)報(bào)錯(cuò):RejectedExecutionException。
后來不用execute方法加入任務(wù),直接getQueue().add(task), 利用其阻塞特性。但是發(fā)現(xiàn)阻塞好用了,但是任務(wù)沒有被處理。一看Queue,暈啊,原來都在里面,任務(wù)池就沒處理它??礃舆€是要走任務(wù)池。
最后自己重載了一個(gè)BlockedThreadPoolExecutor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
private ReentrantLock pauseLock = new ReentrantLock(); private Condition unpaused = pauseLock.newCondition(); @Override public void execute(Runnable command) { pauseLock.lock(); try { while (getPoolSize()==getMaximumPoolSize() && getQueue().remainingCapacity()== 0 ) unpaused.await(); super .execute(command); //放到lock外面的話,在壓力測試下會(huì)有漏網(wǎng)的! } catch (InterruptedException e) { log.warn( this , e); } finally { pauseLock.unlock(); } } @Override protected void afterExecute(Runnable r, Throwable t) { super .afterExecute(r,t); try { pauseLock.lock(); unpaused.signal(); } finally { pauseLock.unlock(); } } |
多線程程序很容易出錯(cuò),寫好了要拼命的用壓力測試,否則問題多多啊~~~
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持,如有疑問請留言或者到本站社區(qū)交流討論!