`

主线程等待线程池所有任务完成

    博客分类:
  • Java
 
阅读更多

原文出处:http://blog.chenlb.com/2008/12/main-thread-wait-all-sub-thread-finish-task-in-thread-pool.html

用线程池编写多线程程序时,当所有任务完成时,要做一些统计的工作。而统计工作必须要在所有任务完成才能做。所以要让主线程等待所有任务完成。可以使用ThreadPoolExecutor.awaitTermination(long timeout, TimeUnit unit)。请看示例代码:

  1. package com.chenlb;  
  2.   
  3. import java.util.Random;  
  4. import java.util.concurrent.LinkedBlockingQueue;  
  5. import java.util.concurrent.ThreadPoolExecutor;  
  6. import java.util.concurrent.TimeUnit;  
  7.   
  8. /** 
  9.  * 线程池使用示例, 主线程等待所有任务完成再结束. 
  10.  * 
  11.  * @author chenlb 2008-12-2 上午10:31:03 
  12.  */  
  13. public class ThreadPoolUse {  
  14.   
  15.     public static class MyTask implements Runnable {  
  16.         private static int id = 0;  
  17.   
  18.         private String name = "task-"+(++id);  
  19.         private int sleep;   
  20.   
  21.         public MyTask(int sleep) {  
  22.             super();  
  23.             this.sleep = sleep;  
  24.         }  
  25.   
  26.         public void run() {  
  27.             System.out.println(name+" -----start-----");  
  28.             try {  
  29.                 Thread.sleep(sleep);    //模拟任务执行.  
  30.             } catch (InterruptedException e) {  
  31.                 e.printStackTrace();  
  32.             }  
  33.             System.out.println(name+" -----end "+sleep+"-----");  
  34.         }  
  35.   
  36.     }  
  37.   
  38.     public static void main(String[] args) {  
  39.         System.out.println("==================start==================");  
  40.         ThreadPoolExecutor executor = new ThreadPoolExecutor(5,560, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());  
  41.         int n = 10;  
  42.         int sleep = 10 * 1000;  //10s  
  43.         Random rm = new Random();  
  44.         for(int i=0; i<n; i++) {  
  45.             executor.execute(new MyTask(rm.nextInt(sleep)+1));  
  46.         }  
  47.   
  48.         executor.shutdown();  
  49.   
  50.         try {  
  51.             boolean loop = true;  
  52.             do {    //等待所有任务完成  
  53.                 loop = !executor.awaitTermination(2, TimeUnit.SECONDS);  
  54.             } while(loop);  
  55.         } catch (InterruptedException e) {  
  56.             e.printStackTrace();  
  57.         }  
  58.   
  59.         System.out.println("==================end====================");  
  60.     }  
  61.   
  62. }  

当然还有其它方法。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics