线程组(读书笔记)

     在一个系统中,如果线程数量很多.而且功能分配比较明确.就可以将相同的功能的线程放在一个线程组里.
public class ThreadGroupName implements Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        String groupAndName = Thread.currentThread().getThreadGroup().getName() + "_" + Thread.currentThread().getName();
        while (true) {
            System.out.println("I am " + groupAndName);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadGroup tg = new ThreadGroup("PrintGroup");
        Thread t1 = new Thread(tg, new ThreadGroupName(), "T1");
        Thread t2 = new Thread(tg, new ThreadGroupName(), "T2");
        t1.start();
        t2.start();
        System.out.println(tg.activeCount());
        tg.list();

    }
}
这里展示了线程组两个重要的功能,activeCount()可以获得活动线程的总数,但由于线程是动态的,因此这个值是估计值,list()方法打印这个线程组中的所有线程的信息!
     线程组里还有一个值得注意的方法stop() 他会停止线程组中所有的线程,他的问题和Thread.stop()相同的问题.
posted @ 2016-12-13 18:33  Darcy_wang  阅读(163)  评论(0编辑  收藏  举报