未来任务被ThreadPoolExecutor

时间:2016-02-11 11:33:13

标签: java java.util.concurrent

我有一个ThreadPoolExecutor,我向它提交了一个任务。

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

此代码将Runnable提交给ThreadPoolExecutor

 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();
}

这里的问题是:当我尝试停止任务时,我遇到以下异常:

  

任务java.util.concurrent.FutureTask@3a475611从java.util.concurrent.ThreadPoolExecutor@216393fb拒绝[已终止,池大小= 0,活动线程= 0,排队任务= 0,已完成任务= 1]

1 个答案:

答案 0 :(得分:7)

问题是你在停止方法中shutdown()激励。如果您只想等待任务完成,请使用Future.get()。关闭执行程序后,无法再向其提交任务。

shutdown()只应在您真正想要终止该应用程序时使用。