2013-07-24 230 views

回答

2

任何人都可以爲我提供一個獲得RejectedExecutionException的例子。可能是一個真實的例子。

肯定。以下代碼將2個作業提交到僅有1個線程正在運行的線程池中。它使用SynchronousQueue這意味着沒有作業將被存儲在作業隊列中。

由於每個作業需要一段時間才能運行,因此第二次執行將填充隊列並引發一個RejectedExecutionException

// create a 1 thread pool with no buffer for the runnable jobs 
ExecutorService threadPool = 
    new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, 
     new SynchronousQueue<Runnable>()); 
// submit 2 jobs that take a while to run 
/// this job takes the only thread 
threadPool.execute(new SleepRunnable()); 
// this tries to put the job into the queue, throws RejectedExecutionException 
threadPool.execute(new SleepRunnable()); 

public class SleepRunnable implements Runnable { 
    public void run() { 
     try { 
      // this just sleeps for a while which pauses the thread 
      Thread.sleep(10000); 
     } catch (InterruptedException e) { 
      Thread.currentThread().interrupt(); 
      return; 
     } 
    } 
} 
+1

你能用文字描述這是什麼原因以及爲什麼,以供將來用戶參考? – hexafraction

+0

完成@hexafraction。 – Gray

+0

完美,謝謝! – hexafraction

3

在調用shutdown(之後,將任務發送給執行程序會引發此異常。

此外,如果執行程序在隊列滿了的情況下使用有界阻塞隊列,則提交任務將不會阻塞,但會以例外情況快速失效。

0

這個問題已經被問和回答: What could be the cause of RejectedExecutionException Submitting tasks to a thread-pool gives RejectedExecutionException

此代碼爲您提供了錯誤,因爲我們試圖啓動任務,但執行程序已關閉,你可以參考上面的鏈接爲進一步解釋答案看起來相當完整:

public class Executorz { 

    public static void main(String[] args) { 
     Executorz ex = new Executorz(); 
     ExecutorService es = Executors.newFixedThreadPool(10); 

     for (int i = 0; i<100 ; i++){ 
      System.out.println("Executed"); 
      es.execute(ex.getNewCountin()); 

      if (i==20) 
       es.shutdown(); 
     } 
    } 

    public Countin getNewCountin(){ 
     return new Countin(); 
    } 

    public class Countin implements Runnable { 
     @Override 
     public void run() { 
      for (double i =0; i<1000000000 ; i++){ 
      }   
      System.out.println("Done"); 
     } 
    } 
}