Java中的ThreadGroup線程組

ThreadGroup概述

在java中爲了方便線程管理出現了線程組ThreadGroup的概念,每一個ThreadGroup能夠同時包含多個子線程和多個子線程組,在一個進程中線程組是以樹形的方式存在,一般狀況下根線程組是system。system線程組下是main線程組,默認狀況下第一級應用本身的線程組是經過main線程組建立出來的。java

public class ThreadGroupTest {

    public static void main(String[] args) throws InterruptedException {
        //主線程對應的線程組
        printGroupInfo(Thread.currentThread());//線程組爲main父線程組爲system

        //新建線程,系統默認的線程組
        Thread appThread = new Thread(()->{},"appThread");
        printGroupInfo(appThread);//線程組爲main父線程組爲system

        //自定義線程組
        ThreadGroup factoryGroup=new ThreadGroup("factory");
        Thread workerThread=new Thread(factoryGroup,()->{},"worker");
        printGroupInfo(workerThread);//線程組爲factory,父線程組爲main

        //設置父線程組
        ThreadGroup deviceGroup=new ThreadGroup(factoryGroup,"device");
        Thread pcThread=new Thread(deviceGroup,()->{},"pc");
        printGroupInfo(pcThread);//線程組爲device,父線程組爲factory

    }

    static void printGroupInfo(Thread t) {
        ThreadGroup group = t.getThreadGroup();
        System.out.println("thread " + t.getName()
                + " group name is "+ group.getName()
                + " max priority is " + group.getMaxPriority()
                + " thread count is " + group.activeCount()
                + " parent group is "+ (group.getParent()==null?null:group.getParent().getName()));

        ThreadGroup parent=group;
        do {
            ThreadGroup current = parent;
            parent = parent.getParent();
            if (parent == null) {
                break;
            }
            System.out.println(current.getName() +" Group's  parent group name is "+parent.getName());

        } while (true);
        System.out.println("--------------------------");
    }

}

ThreadGroup線程組的操做

線程組信息的獲取app

public int activeCount(); // 得到當前線程組中線程數目, 包括可運行和不可運行的
public int activeGroupCount(); //得到當前線程組中活動的子線程組的數目
public int enumerate(Thread list[]); //列舉當前線程組中的線程
public int enumerate(ThreadGroup list[]); //列舉當前線程組中的子線程組
public final int getMaxPriority(); //得到當前線程組中最大優先級
public final String getName(); //得到當前線程組的名字
public final ThreadGroup getParent(); //得到當前線程組的父線程組
public boolean parentOf(ThreadGroup g); //判斷當前線程組是否爲指定線程的父線程
public boolean isDaemon(); //判斷當前線程組中是否有監護線程
public void list(); //列出當前線程組中全部線程和子線程名

線程組的操做dom

public final void resume(); //使被掛起的當前組內的線程恢復到可運行狀態
public final void setDaemon (boolean daemon); //指定一個線程爲當前線程組的監護線程
public final void setMaxPriority(int pri); //設置當前線程組容許的最大優先級
public final void stop();//終止當前線程組中全部線程
public final void suspend(); //掛起當前線程組中全部線程
public String toStrinng(); //將當前線程組轉換爲String類的對象
public class ThreadGroupDemo {

    public static void main(String[] args) throws InterruptedException {
        // 建立5個線程,併入group裏面進行管理
        ThreadGroup threadGroup = new ThreadGroup("threadGroupTest1");
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(threadGroup,()->{
                System.out.println("Thread Start " + Thread.currentThread().getName());
                try {
                    int value = (int)new Random((new Date()).getTime()).nextDouble()*100;
                    System.out.printf("Thread %s doTask: %d\n", Thread.currentThread().getName(),value);
                    TimeUnit.SECONDS.sleep(value);
                } catch (InterruptedException e) {
                    System.out.printf("Thread %s: Interrupted\n", Thread.currentThread().getName());
                    return;
                }
                System.out.println("Thread end " + Thread.currentThread().getName());
            });
            thread.start();
            TimeUnit.SECONDS.sleep(1);
        }
        //group信息
        System.out.printf("Number of Threads: %d\n", threadGroup.activeCount());
        System.out.printf("Information about the Thread Group\n");
        threadGroup.list();

        //複製group的thread信息
        Thread[] threads = new Thread[threadGroup.activeCount()];
        threadGroup.enumerate(threads);
        for (int i = 0; i < threadGroup.activeCount(); i++) {
            System.out.printf("Thread %s: %s\n", threads[i].getName(),threads[i].getState());
        }

        //等待結束
        while (threadGroup.activeCount() > 9) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //中斷group中的線程
        threadGroup.interrupt();
    }
}

參考地址:.net

相關文章
相關標籤/搜索