ThreadGroup thread group in Java

ThreadGroup overview

In java, in order to facilitate thread management, the concept of thread group appears. Each thread group can contain multiple sub threads and multiple sub thread groups at the same time. In a process, the thread group exists in the form of tree, usually the root thread group is system. The system thread group is the main thread group. By default, the first level application's own thread group is created through the main thread group.

public class ThreadGroupTest {

    public static void main(String[] args) throws InterruptedException {
        //Thread group corresponding to main thread
        printGroupInfo(Thread.currentThread());//Thread group is main, parent thread group is system

        //New thread, system default thread group
        Thread appThread = new Thread(()->{},"appThread");
        printGroupInfo(appThread);//Thread group is main, parent thread group is system

        //Custom thread group
        ThreadGroup factoryGroup=new ThreadGroup("factory");
        Thread workerThread=new Thread(factoryGroup,()->{},"worker");
        printGroupInfo(workerThread);//The thread group is factory, and the parent thread group is main

        //Set parent thread group
        ThreadGroup deviceGroup=new ThreadGroup(factoryGroup,"device");
        Thread pcThread=new Thread(deviceGroup,()->{},"pc");
        printGroupInfo(pcThread);//Thread group is device, parent thread group is 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("--------------------------");
    }

}

Operation of ThreadGroup thread group

Getting thread group information

public int activeCount(); // Gets the number of threads in the current thread group, including runnable and non runnable
public int activeGroupCount(); //Gets the number of active child thread groups in the current thread group
public int enumerate(Thread list[]); //Enumerate threads in the current thread group
public int enumerate(ThreadGroup list[]); //Enumerates child thread groups in the current thread group
public final int getMaxPriority(); //Get the maximum priority in the current thread group
public final String getName(); //Get the name of the current thread group
public final ThreadGroup getParent(); //Get the parent thread group of the current thread group
public boolean parentOf(ThreadGroup g); //Determine whether the current thread group is the parent of the specified thread
public boolean isDaemon(); //Determine whether there are monitoring threads in the current thread group
public void list(); //Lists all thread and sub thread names in the current thread group

Operation of thread group

public final void resume(); //Returns a thread in the current suspended group to a runnable state
public final void setDaemon (boolean daemon); //Specify a thread as the guardian thread of the current thread group
public final void setMaxPriority(int pri); //Set the maximum priority allowed for the current thread group
public final void stop();//Terminate all threads in the current thread group
public final void suspend(); //Suspend all threads in the current thread group
public String toStrinng(); //Converts the current thread group to an object of the String class
public class ThreadGroupDemo {

    public static void main(String[] args) throws InterruptedException {
        // Create 5 threads and merge them into the group for management
        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 information
        System.out.printf("Number of Threads: %d\n", threadGroup.activeCount());
        System.out.printf("Information about the Thread Group\n");
        threadGroup.list();

        //Copy the thread information of the group
        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());
        }

        //Waiting for the end
        while (threadGroup.activeCount() > 9) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //Break thread in group
        threadGroup.interrupt();
    }
}

Reference address:

Keywords: Java

Added by fxb9500 on Sat, 04 Jan 2020 16:41:26 +0200