利用ThreadGroup等待所有线程执行结束

import java.util.Random;

/**
 *利用ThreadGroup等待所有线程执行结束
 */
public class T {

    public static void main(String[] args) {
        
        ThreadGroup group1 = new ThreadGroup("group-one");
        for(int i=1; i<=10; i++){
            new Thread(group1, new GroupThreadMem(),i+"#线程").start();
        }
        while(group1.activeCount() > 0){
        //    System.out.println("group1的当前的活跃数量:"+group1.activeCount());
        }
        System.out.println("==group1中所有线程执行结束===");
    }

}

class GroupThreadMem implements Runnable {

    @Override
    public void run() {
        int times = new Random().nextInt(10);
        while(times-- > 0){
            try {
                Thread.sleep(50);
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    
}

 

posted on 2013-01-05 11:17  cfd406635982  阅读(2057)  评论(0编辑  收藏  举报