2016-02-11 50 views
5

我有一個ThreadPoolExecutor,我向它提交了一個任務。從ThreadPoolExecutor拒絕的未來任務

private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1)); 

此代碼提交RunnableThreadPoolExecutor

protected void waitAndSweep(final String symbol) { 

    runnable = new Runnable() { 
     public void run() { /* irrelevant code */ } 
    }; 

    try { 
     Future<?> self = threadPoolExecutor.submit(runnable); 
     futures.add(self); 
    } catch (RejectedExecutionException re) { 
     /* this exception will be thrown when wait and sweep is called more than twice. 
     * threadPoolExecutor can have one running task and one waiting task. 
     */ 
    } catch (Exception e) { 
     logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol, "Exception caught...", e); 
    } 
    } 

以下代碼將停止該任務。

protected synchronized void stop(StrategyEntry entry) throws Exception { 
    for (Object future : futures) { 
     ((Future<?>) future).cancel(true); 
    } 
    futures.clear(); 

    threadPoolExecutor.shutdown(); 
} 

這裏的問題是:當我試圖停止任務,我得到以下異常:

任務[email protected]從java.util.concurrent的拒絕。的ThreadPoolExecutor @ 216393fb [終止,池大小= 0,活動線程= 0,隊列任務= 0,完成的任務= 1]

+0

你是否在這個執行器的任何地方調用'shutdown()'? – RAnders00

+0

是在停止方法 – MMPgm

+0

您正在創建容量爲1的後備隊列 - 是否存在其他一些任務? –

回答

5

的問題是,你shutdown()在停止方法的excutor。如果您只是想等待任務完成,請使用Future.get()。當執行者關閉時,任務不能再提交給它。

shutdown()只應在您實際想要終止應用程序時使用。

+0

當執行器關閉時,我不想要提交任何新任務 – MMPgm

+0

@MMPgm從你的問題,它不是完全清楚你所期望的'stop()實際上做的方法。也許你可以澄清? – RAnders00

+0

停止方法應該終止所有等待的任務,並且不應該接受任何其他任務。我只是想知道發生異常的可能情況。 – MMPgm

相關問題