ThreadPoolExecutor 的 shutdown() 和shutdownNow()

来源:互联网 发布:苹果手机涂鸦软件 编辑:程序博客网 时间:2024/05/20 18:48

 

 

    public List<Runnable> shutdownNow() {
        List<Runnable> tasks;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(STOP);
          
  interruptWorkers();
            tasks = drainQueue();
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
        return tasks;
    }

    public void shutdown() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(SHUTDOWN);
      
      interruptIdleWorkers();
            onShutdown(); // hook for ScheduledThreadPoolExecutor
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
    }

 

对比其代码可知 shutdown 只是将空闲的线程interrupt() 了, 因此在shutdown()之前提交的任务可以继续执行直到结束。

而shutdownNow 是interrupt所有线程, 因此大部分线程将立刻被中断。之所以是大部分,而不是全部 ,是因为interrupt()方法能力有限。

如果线程中没有sleep 、wait、Condition、定时锁等应用, interrupt()方法是无法中断当前的线程的。所以,ShutdownNow()并不代表线程池就一定立即就能退出,它可能必须要等待所有正在执行的任务都执行完成了才能退出。

例如下面这种情况 将一直打印 go to sleep

package edu.neu.xiaobing.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Interrupt {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  ExecutorService executor  = Executors.newCachedThreadPool();
  executor.execute(new Interrupt().new MyRunnable());
  executor.shutdownNow();
 }
 
 
 class MyRunnable implements Runnable{

  @Override
  public void run() {
   // TODO Auto-generated method stub
   while(true){
    System.out.println("go to sleep");
//    try {
//     
//     Thread.sleep(100000);
//     
//    } catch (InterruptedException e) {
//     // TODO Auto-generated catch block
//     e.printStackTrace();
//     System.out.println("sleeping");
//    }
   }
  }
  
  
 }

}

 

 

 

原创粉丝点击