16.ThreadGroup线程组

public class ThreadGroupDemo implements Runnable{
    public static void main(String[] args){
        //建立一个名为"GroupName"的线程组
        ThreadGroup group = new ThreadGroup("GroupName");
        //将T1,T2两个线程加入组中
        Thread thread1 = new Thread(group,new ThreadGroupDemo(),"T1");
        Thread thread2 = new Thread(group,new ThreadGroupDemo(),"T2");
        thread1.start();
        thread2.start();
        //获得活动线程的总数
        System.out.println(group.activeCount());
        //线程组中所有的线程信息
        group.list();
    }
    @Override
    public void run() {
        String s = Thread.currentThread().getThreadGroup().getName() + "-" + Thread.currentThread().getName();
        while (true){
            System.out.println("I am "+s);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //I am GroupName-T1
    //I am GroupName-T2
    //2
    //java.lang.ThreadGroup[name=GroupName,maxpri=10]
    //    Thread[T1,5,GroupName]
    //    Thread[T2,5,GroupName]
    //I am GroupName-T1
    //I am GroupName-T2
    //I am GroupName-T1
    //I am GroupName-T2
    //I am GroupName-T1
    //I am GroupName-T2
}
posted @ 2019-08-20 16:10  fly_bk  阅读(175)  评论(0编辑  收藏  举报