(转)ExecutorService对象的shutdown()和shutdownNow()的区别

http://bijian1013.iteye.com/blog/2281156

 从上篇文章的实例中,我们用了ExecutorService的shutdown方法,但我们不难发现它还有shutdownNow方法,它们到底有什么区别呢?

        这两个方法都可以关闭 ExecutorService,这将导致其拒绝新任务。shutdown() 方法在终止前允许执行以前提交的任务,而 shutdownNow() 方法阻止等待任务启动并试图停止当前正在执行的任务。在终止时,执行程序没有任务在执行,也没有任务在等待执行,并且无法提交新任务。应该关闭未使用的 ExecutorService 以允许回收其资源。 

        下列方法分两个阶段关闭 ExecutorService。第一阶段调用 shutdown 拒绝传入任务,然后调用 shutdownNow(如有必要)取消所有遗留的任务:

Java代码 

 收藏代码

  1. private static void shutdownAndAwaitTermination(ExecutorService pool) {  
  2.     pool.shutdown(); // Disable new tasks from being submitted  
  3.     try {  
  4.         // Wait a while for existing tasks to terminate  
  5.         if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {  
  6.             pool.shutdownNow(); // Cancel currently executing tasks  
  7.             // Wait a while for tasks to respond to being cancelled  
  8.             if (!pool.awaitTermination(60, TimeUnit.SECONDS))  
  9.                 System.err.println("Pool did not terminate");  
  10.         }  
  11.     } catch (InterruptedException ie) {  
  12.         // (Re-)Cancel if current thread also interrupted  
  13.         pool.shutdownNow();  
  14.         // Preserve interrupt status  
  15.         Thread.currentThread().interrupt();  
  16.     }  
  17. }  

        下面我们以上篇文章的实例来做测试验证:

1.在submit(task2)后shutdown()

Java代码 

 收藏代码

  1. package com.bijian.study;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutorService;  
  5. import java.util.concurrent.Executors;  
  6. import java.util.concurrent.Future;  
  7.   
  8. /**  
  9.  * Callable 和 Future接口 
  10.  * Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。 
  11.  * Callable和Runnable有几点不同: 
  12.  * (1)Callable规定的方法是call(),而Runnable规定的方法是run(). 
  13.  * (2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。 
  14.  * (3)call()方法可抛出异常,而run()方法是不能抛出异常的。 
  15.  * (4)运行Callable任务可拿到一个Future对象,Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。 
  16.  */  
  17. public class CallableAndFuture {  
  18.   
  19.     public static class MyCallable implements Callable {  
  20.   
  21.         private int flag = 0;  
  22.   
  23.         public MyCallable(int flag) {  
  24.             this.flag = flag;  
  25.         }  
  26.   
  27.         public String call() throws Exception {  
  28.   
  29.             if (this.flag == 0) {  
  30.                 return "flag = 0";  
  31.             }  
  32.             if (this.flag == 1) {  
  33.                 try {  
  34.                     while (true) {  
  35.                         System.out.println("looping.");  
  36.                         Thread.sleep(2000);  
  37.                     }  
  38.                 } catch (InterruptedException e) {  
  39.                     System.out.println("Interrupted");  
  40.                 }  
  41.                 return "false";  
  42.             } else {  
  43.                 throw new Exception("Bad flag value!");  
  44.             }  
  45.         }  
  46.     }  
  47.   
  48.     public static void main(String[] args) {  
  49.   
  50.         // 定义3个Callable类型的任务  
  51.         MyCallable task1 = new MyCallable(0);  
  52.         MyCallable task2 = new MyCallable(1);  
  53.         MyCallable task3 = new MyCallable(2);  
  54.   
  55.         // 创建一个执行任务的服务  
  56.         ExecutorService es = Executors.newFixedThreadPool(3);  
  57.         try {  
  58.             // 提交并执行任务,任务启动时返回了一个Future对象,  
  59.             // 如果想得到任务执行的结果或者是异常可对这个Future对象进行操作  
  60.             Future future1 = es.submit(task1);  
  61.             // 获得第一个任务的结果,如果调用get方法,当前线程会等待任务执行完毕后才往下执行  
  62.             System.out.println("task1: " + future1.get());  
  63.   
  64.             Future future2 = es.submit(task2);  
  65.               
  66.             es.shutdown();  
  67.               
  68.             // 等待5秒后,再停止第二个任务。因为第二个任务进行的是无限循环  
  69.             Thread.sleep(5000);  
  70.             System.out.println("task2 cancel: " + future2.cancel(true));  
  71.               
  72.             // 获取第三个任务的输出,因为执行第三个任务会引起异常  
  73.             // 所以下面的语句将引起异常的抛出  
  74.             Future future3 = es.submit(task3);  
  75.             System.out.println("task3: " + future3.get());  
  76.         } catch (Exception e) {  
  77.             System.out.println(e.toString());  
  78.         }  
  79.         // 停止任务执行服务  
  80.         //es.shutdown();  
  81.     }  
  82. }  

        运行结果:

Text代码 

 收藏代码

  1. task1: flag = 0  
  2. looping.  
  3. looping.  
  4. looping.  
  5. task2 cancel: true  
  6. java.util.concurrent.RejectedExecutionException  
  7. Interrupted  

2.在submit(task2)后shutdownNow()

Java代码 

 收藏代码

  1. package com.bijian.study;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutorService;  
  5. import java.util.concurrent.Executors;  
  6. import java.util.concurrent.Future;  
  7.   
  8. /**  
  9.  * Callable 和 Future接口 
  10.  * Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。 
  11.  * Callable和Runnable有几点不同: 
  12.  * (1)Callable规定的方法是call(),而Runnable规定的方法是run(). 
  13.  * (2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。 
  14.  * (3)call()方法可抛出异常,而run()方法是不能抛出异常的。 
  15.  * (4)运行Callable任务可拿到一个Future对象,Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。 
  16.  */  
  17. public class CallableAndFuture {  
  18.   
  19.     public static class MyCallable implements Callable {  
  20.   
  21.         private int flag = 0;  
  22.   
  23.         public MyCallable(int flag) {  
  24.             this.flag = flag;  
  25.         }  
  26.   
  27.         public String call() throws Exception {  
  28.   
  29.             if (this.flag == 0) {  
  30.                 return "flag = 0";  
  31.             }  
  32.             if (this.flag == 1) {  
  33.                 try {  
  34.                     while (true) {  
  35.                         System.out.println("looping.");  
  36.                         Thread.sleep(2000);  
  37.                     }  
  38.                 } catch (InterruptedException e) {  
  39.                     System.out.println("Interrupted");  
  40.                 }  
  41.                 return "false";  
  42.             } else {  
  43.                 throw new Exception("Bad flag value!");  
  44.             }  
  45.         }  
  46.     }  
  47.   
  48.     public static void main(String[] args) {  
  49.   
  50.         // 定义3个Callable类型的任务  
  51.         MyCallable task1 = new MyCallable(0);  
  52.         MyCallable task2 = new MyCallable(1);  
  53.         MyCallable task3 = new MyCallable(2);  
  54.   
  55.         // 创建一个执行任务的服务  
  56.         ExecutorService es = Executors.newFixedThreadPool(3);  
  57.         try {  
  58.             // 提交并执行任务,任务启动时返回了一个Future对象,  
  59.             // 如果想得到任务执行的结果或者是异常可对这个Future对象进行操作  
  60.             Future future1 = es.submit(task1);  
  61.             // 获得第一个任务的结果,如果调用get方法,当前线程会等待任务执行完毕后才往下执行  
  62.             System.out.println("task1: " + future1.get());  
  63.   
  64.             Future future2 = es.submit(task2);  
  65.               
  66.             es.shutdownNow();  
  67.               
  68.             // 等待5秒后,再停止第二个任务。因为第二个任务进行的是无限循环  
  69.             Thread.sleep(5000);  
  70.             System.out.println("task2 cancel: " + future2.cancel(true));  
  71.               
  72.             // 获取第三个任务的输出,因为执行第三个任务会引起异常  
  73.             // 所以下面的语句将引起异常的抛出  
  74.             Future future3 = es.submit(task3);  
  75.             System.out.println("task3: " + future3.get());  
  76.         } catch (Exception e) {  
  77.             System.out.println(e.toString());  
  78.         }  
  79.         // 停止任务执行服务  
  80.         //es.shutdown();  
  81.     }  
  82. }  

        运行结果:

Text代码 

 收藏代码

  1. task1: flag = 0  
  2. looping.  
  3. Interrupted  
  4. task2 cancel: false  
  5. java.util.concurrent.RejectedExecutionException  

        当然,我们也可以分两个阶段关闭 ExecutorService。第一阶段调用 shutdown 拒绝传入任务,然后调用 shutdownNow(如有必要)取消所有遗留的任务。修改此实例如下:

Java代码 

 收藏代码

  1. package com.bijian.study;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutorService;  
  5. import java.util.concurrent.Executors;  
  6. import java.util.concurrent.Future;  
  7. import java.util.concurrent.TimeUnit;  
  8.   
  9. /**  
  10.  * Callable 和 Future接口 
  11.  * Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。 
  12.  * Callable和Runnable有几点不同: 
  13.  * (1)Callable规定的方法是call(),而Runnable规定的方法是run(). 
  14.  * (2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。 
  15.  * (3)call()方法可抛出异常,而run()方法是不能抛出异常的。 
  16.  * (4)运行Callable任务可拿到一个Future对象,Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。 
  17.  */  
  18. public class CallableAndFuture {  
  19.   
  20.     public static class MyCallable implements Callable {  
  21.   
  22.         private int flag = 0;  
  23.   
  24.         public MyCallable(int flag) {  
  25.             this.flag = flag;  
  26.         }  
  27.   
  28.         public String call() throws Exception {  
  29.   
  30.             if (this.flag == 0) {  
  31.                 return "flag = 0";  
  32.             }  
  33.             if (this.flag == 1) {  
  34.                 try {  
  35.                     while (true) {  
  36.                         System.out.println("looping.");  
  37.                         Thread.sleep(2000);  
  38.                     }  
  39.                 } catch (InterruptedException e) {  
  40.                     System.out.println("Interrupted");  
  41.                 }  
  42.                 return "false";  
  43.             } else {  
  44.                 throw new Exception("Bad flag value!");  
  45.             }  
  46.         }  
  47.     }  
  48.   
  49.     public static void main(String[] args) {  
  50.   
  51.         // 定义3个Callable类型的任务  
  52.         MyCallable task1 = new MyCallable(0);  
  53.         MyCallable task2 = new MyCallable(1);  
  54.         MyCallable task3 = new MyCallable(2);  
  55.   
  56.         // 创建一个执行任务的服务  
  57.         ExecutorService es = Executors.newFixedThreadPool(3);  
  58.         try {  
  59.             // 提交并执行任务,任务启动时返回了一个Future对象,  
  60.             // 如果想得到任务执行的结果或者是异常可对这个Future对象进行操作  
  61.             Future future1 = es.submit(task1);  
  62.             // 获得第一个任务的结果,如果调用get方法,当前线程会等待任务执行完毕后才往下执行  
  63.             System.out.println("task1: " + future1.get());  
  64.   
  65.             Future future2 = es.submit(task2);  
  66.               
  67.             shutdownAndAwaitTermination(es);  
  68.               
  69.             // 等待5秒后,再停止第二个任务。因为第二个任务进行的是无限循环  
  70.             Thread.sleep(5000);  
  71.             System.out.println("task2 cancel: " + future2.cancel(true));  
  72.               
  73.             // 获取第三个任务的输出,因为执行第三个任务会引起异常  
  74.             // 所以下面的语句将引起异常的抛出  
  75.             Future future3 = es.submit(task3);  
  76.             System.out.println("task3: " + future3.get());  
  77.         } catch (Exception e) {  
  78.             System.out.println(e.toString());  
  79.         }  
  80.         // 停止任务执行服务  
  81.         //es.shutdown();  
  82.           
  83.     }  
  84.       
  85.     private static void shutdownAndAwaitTermination(ExecutorService pool) {  
  86.         pool.shutdown(); // Disable new tasks from being submitted  
  87.         try {  
  88.             // Wait a while for existing tasks to terminate  
  89.             if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {  
  90.                 pool.shutdownNow(); // Cancel currently executing tasks  
  91.                 // Wait a while for tasks to respond to being cancelled  
  92.                 if (!pool.awaitTermination(10, TimeUnit.SECONDS))  
  93.                     System.err.println("Pool did not terminate");  
  94.             }  
  95.         } catch (InterruptedException ie) {  
  96.             // (Re-)Cancel if current thread also interrupted  
  97.             pool.shutdownNow();  
  98.             // Preserve interrupt status  
  99.             Thread.currentThread().interrupt();  
  100.         }  
  101.     }  
  102. }  

        运行结果:

Text代码 

 收藏代码

  1. task1: flag = 0  
  2. looping.  
  3. looping.  
  4. looping.  
  5. looping.  
  6. looping.  
  7. looping.  
  8. Interrupted  
  9. task2 cancel: false  
  10. java.util.concurrent.RejectedExecutionException  

猜你喜欢

转载自blog.csdn.net/moxiyuyan1994/article/details/82966136
今日推荐