1、當一個有限隊列充滿後,線程池的飽和策略開始起作用。
2、ThreadPoolExecutor的飽和策略通過調用setRejectedExecutionHandler來修改。不同的飽和策略如下:
1)AbortPolicy:中止,executor拋出未檢查RejectedExecutionException,調用者捕獲這個異常,然後自己編寫能滿足自己需求的處理代碼。
2)DiscardRunsPolicy:遺棄最舊的,選擇丟棄的任務,是本應接下來就執行的任務。
3)DiscardPolicy:遺棄會預設放棄最新提交的任務(這個任務不能進入隊列等待執行時)
4)CallerRunsPolicy:調用者運行,既不會丟棄哪個任務,也不會拋出任何異常,把一些任務推回到調用者那裡,以此減緩新任務流。它不會在池線程中執行最新提交的任務,但它會在一個調用了execute的線程中執行。
3、建立一個可變長的線程池,使用受限隊列和調用者運行飽和策略。
ThreadPoolExecutor executor=new ThreadPoolExecutor(N_THREADS,N_THREADS,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(CAPACITY));
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
4、當線程隊列充滿後,並沒有預置的飽和策略來阻塞execute。但是,使用Semaphore訊號量可以實現這個效果。Semaphore會限制任務注入率。
@ThreadSafe
public class BoundedExecutor{
private final Executor exec;
private final Semaphore semaphore;
public BoundedExecutor(Executor exec,int bound){
this.exec=exec;
this.semaphore=new Semaphore(bound);
}
public void submitTask(final Runnable command) throws InterruptedException{
semaphore.acquire();
try{
exec.execute(new Runnable(){
public void run(){
try{
command.run();
}
finally{
semaphore.release();
}
}
});
}catch (RejectedExecutionException e){
semaphore.release();
}
}
}
from:http://blog.csdn.net/yangdengfeng2003/archive/2009/04/01/4042274.aspx