2013-10-10 41 views
1

我需要覆蓋執行程序的執行方法,我需要改變線程的行爲,只有在隊列滿時纔會創建核心池大小。覆蓋Executor的執行方法

但是,在實時應用程序中,這種行爲是不受歡迎的,因爲它可能會導致隊列中出現的任務不斷等待。

我已經改變了執行如下方法:

public void execute(Runnable command) 
    { 
     System.out.println("ActiveCount : " + getActiveCount() + " PoolSize : " + getPoolSize() 
        + " QueueSize : " + getQueue().size() +" Idle Threads : " +(getPoolSize()-getActiveCount())); 





int c = ctl.get(); 
       if (workerCountOf(c) < corePoolSize) { 
        if (addWorker(command, true)) 
         return; 
        c = ctl.get(); 
       } 
    else if (isRunning(c) && workQueue.offer(command)) 
    { 
     int recheck = ctl.get(); 

    if (getActiveCount() < workerCountOf(recheck) && isRunning(recheck) && workQueue.offer(command)) { 
      return; 
     } 
    if (addWorker(command, false)) { 
       return; 
     }  
    else if (! isRunning(recheck) && remove(command)) 
     { 
       reject(command); 
     } 
    else if (workerCountOf(recheck) == 0) 
     { 
       addWorker(null, false); 
     } 
    } 
    else 
    { 
     reject(command); // add task to the queue 


    } 
} 

試圖實現: CoreThreads - >非CoreThreads - >隊列的代替CoreThreads - >隊列 - >非CoreThreads。

+0

是不是它的默認行爲..一旦隊列已滿,那麼只有線程池創建新線程。 –

+1

這聽起來像你正在使用線程池,然後。 –

+0

我覺得在他的情況下,需要利用線程來最大化池大小,並且如果不能創建新的線程,那麼必須使用隊列來等待任何線程被釋放......我知道這不是池默認行爲,但一般來說,這是常見的要求。 – Batty

回答

1

我不明白爲什麼你需要改變執行方法,我認爲,最大池大小不應該優先於隊列,因爲我可以看到你的代碼。

我有同樣的問題,你可以按照鏈接:

click to follow the thread.

我覺得這應該是你最後的選擇,嘗試別的東西第一。