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

时间:2021-11-06 18:28:47
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();
            }
        }
    }
    
    
}