java線程--線程組

線程組例子

public class Test {
    public static void main(String[] args) {
        ThreadGroup tg = new ThreadGroup("group");
        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();
    }

    static class ThreadGroupName implements Runnable {

        @Override
        public void run() {
            String groupAndName = Thread.currentThread().getThreadGroup() +
                    " : " + Thread.currentThread().getName();
            while (true) {
                System.out.println("i am " + groupAndName);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
相關文章
相關標籤/搜索