2010-06-08 163 views
5

與Quartz Scheduler一起提供的SimpleThreadPool類不具有FIFO行爲。我想確保我是否繼續向調度程序添加作業,它們是以先進先出的方式處理的。有沒有任何ThreadPool可用於此?或者還有其他方法可以實現嗎?石英調度程序theadpool

回答

5

你可以通過委託給一個FIFO隊列的ThreadPoolExecutor實現這一點,如下所示:

public class DelegatingThreadPool implements ThreadPool { 

private int size = 5; //Fix this up if you like 
private final ThreadPoolExecutor executor = new ThreadPoolExecutor(size, size, 
            0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); 

public boolean runInThread(Runnable runnable) { 
    synchronized (executor) { 
     if (executor.getActiveCount() == size) { 
      return false; 
     } 
     executor.submit(runnable); 
     return true; 
    } 
} 

public int blockForAvailableThreads() { 
    synchronized (executor) { 
     return executor.getActiveCount(); 
    } 
} 

public void initialize() throws SchedulerConfigException { 
    //noop 
} 

public void shutdown(boolean waitForJobsToComplete) { 
    //No impl provided for wait, write one if you like 
    executor.shutdownNow(); 
} 

public int getPoolSize() { 
    return size; 
} 

public void setInstanceId(String schedInstId) { 
    //Do what you like here 
} 

public void setInstanceName(String schedName) { 
    //Do what you like here 
} 

這可能是可執行文件的有效數量將不被執行任務的確切數量完全一致。您需要添加一個鎖存器並使用beforeExecute來確保 該任務在需要時已開始運行。

+0

這是一個很好的例子,我會試試這個。 – Shamik 2010-06-08 17:24:01