在执行程序关闭后,为什么Runnable仍在可执行的线程池执行程序中执行?

时间:2017-06-22 12:19:49

标签: java multithreading threadpool

我有一个可调试的线程池执行程序实现,就像在ThreadPoolExecutor类的文档中一样。我有一个简单的测试,它执行以下操作:

class PausableThreadPoolExecutor extends ThreadPoolExecutor {
  public static PausableThreadPoolExecutor newSingleThreadExecutor() {
    return new PausableThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>());
  }

  /** isPaused */
  private boolean isPaused;

  /** pauseLock */
  private ReentrantLock pauseLock = new ReentrantLock();

  /** unpaused */
  private Condition unpaused = this.pauseLock.newCondition();

  public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
      TimeUnit unit, BlockingQueue<Runnable> workQueue) {
    super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
  }

  @Override
  protected void beforeExecute(Thread t, Runnable r) {
    super.beforeExecute(t, r);
    this.pauseLock.lock();
    try {
      while (this.isPaused) {
        this.unpaused.await();
      }
    } catch (InterruptedException ie) {
      t.interrupt();
    } finally {
      this.pauseLock.unlock();
    }
  }

  public void pause() {
    this.pauseLock.lock();
    try {
      this.isPaused = true;
    } finally {
      this.pauseLock.unlock();
    }
  }

  public void resume() {
    this.pauseLock.lock();
    try {
      this.isPaused = false;
      this.unpaused.signalAll();
    } finally {
      this.pauseLock.unlock();
    }
  }

  public static void main(String[] args) {
    PausableThreadPoolExecutor p = PausableThreadPoolExecutor.newSingleThreadExecutor();
    p.pause();
    p.execute(new Runnable() {

      public void run() {
        for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
          System.out.println(ste);
        }
      }
    });
    p.shutdownNow();
  }
}

有趣的是,对shutDownNow的调用将导致Runnable运行。这是正常的吗?据我所知,shutDownNow将尝试通过中断它们来停止正在执行的任务。但是中断似乎唤醒了执行它的任务。有人可以解释一下吗?

1 个答案:

答案 0 :(得分:1)

  

有趣的是,对shutDownNow的调用将导致Runnable运行。这是正常的吗?

不确定它是否“正常”,但鉴于您的代码肯定是预期的。在您的beforeExecute(...)方法中,我看到以下内容:

    this.pauseLock.lock();
    try {
        while (this.isPaused) {
            this.unpaused.await();
        }
    } catch (InterruptedException ie) {
        t.interrupt();
    } finally {
        this.pauseLock.unlock();
    }

该作业将等待isPaused布尔值设置为false。但是,如果作业被中断,this.unpaused.await()将抛出InterruptedException循环中的while,则重新中断该线程,这始终是一个好的模式,beforeExecute()返回,并允许该作业执行。除非你有特定的代码来处理中断,否则中断线程不会杀死它。

如果要在作业中断时停止作业,那么当您看到作业被中断时,您可以在RuntimeException处理程序中抛出beforeExecute()

} catch (InterruptedException ie) {
    t.interrupt();
    throw new RuntimeException("Thread was interrupted so don't run");

更简洁的方法可能是检查您是否在run()方法中被中断然后退出:

public void run() {
   if (Thread.currentThread().isInterrupted()) {
      return;
   }
   ...