2013-10-10 44 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.

我觉得这应该是你最后的选择,尝试别的东西第一。