awaitTermination() shutdown()

来源:互联网 发布:java中线程的生命周期 编辑:程序博客网 时间:2024/05/03 20:51

newFixedThreadPool

创建一个固定大小的线程池。

shutdown():用于关闭启动线程,如果不调用该语句,jvm不会关闭。

awaitTermination():用于等待子线程结束,再继续执行下面的代码。该例中我设置一直等着子线程结束。

 

 

Java代码 复制代码 收藏代码
  1. public class Test {   
  2.   
  3.     public static void main(String[] args) throws IOException, InterruptedException {   
  4.         ExecutorService service = Executors.newFixedThreadPool(2);   
  5.         for (int i = 0; i < 4; i++) {   
  6.             Runnable run = new Runnable() {   
  7.                 @Override  
  8.                 public void run() {   
  9.                     System.out.println("thread start");   
  10.                 }   
  11.             };   
  12.             service.execute(run);   
  13.         }   
  14.         service.shutdown();   
  15.         service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);   
  16.         System.out.println("all thread complete");   
  17.     }   
  18. }  

 

 

 

 输出:
thread start
thread start
thread start
thread start
all thread complete