ExecutorService接口作为Java中一个常用到的接口,怎么实现的?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
ExecutorService接口是Executor接口的子接口,并添加了管理生命周期的功能。 请考虑以下示例代码:
import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.TimeUnit;
public class TestThread {
 public static void main(final String[] arguments) throws InterruptedException {
 ExecutorService e = Executors.newSingleThreadExecutor();
  try {  
     e.submit(new Thread());  
     System.out.println("Shutdown executor");  
     e.shutdown();  
     e.awaitTermination(5, TimeUnit.SECONDS);  
  } catch (InterruptedException ex) {  
     System.err.println("tasks interrupted");  
  } finally {  
     if (!e.isTerminated()) {  
        System.err.println("cancel non-finished tasks");  
     }  
     e.shutdownNow();  
     System.out.println("shutdown finished");  
  }  
 
}
static class Task implements Runnable {
  public void run() {  
     try {  
        Long duration = (long) (Math.random() * 20);  
        System.out.println("Running Task!");  
        TimeUnit.SECONDS.sleep(duration);  
     } catch (InterruptedException ex) {  
        ex.printStackTrace();  
     }  
  }  
 
}
 } Java
执行上面示例代码,得到以下结果:
Shutdown executor shutdown finished
      
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.TimeUnit;  
  
public class TestThread {  
   public static void main(final String[] arguments) throws InterruptedException {  
      ExecutorService e = Executors.newSingleThreadExecutor();  
  
      try {  
         e.submit(new Thread());  
         System.out.println("Shutdown executor");  
         e.shutdown();  
         e.awaitTermination(5, TimeUnit.SECONDS);  
      } catch (InterruptedException ex) {  
         System.err.println("tasks interrupted");  
      } finally {  
  
         if (!e.isTerminated()) {  
            System.err.println("cancel non-finished tasks");  
         }  
         e.shutdownNow();  
         System.out.println("shutdown finished");  
      }  
   }  
  
   static class Task implements Runnable {  
        
      public void run() {  
           
         try {  
            Long duration = (long) (Math.random() * 20);  
            System.out.println("Running Task!");  
            TimeUnit.SECONDS.sleep(duration);  
         } catch (InterruptedException ex) {  
            ex.printStackTrace();  
         }  
      }  
   }         
}