Java Concurrent Programming: ThreadGroup

Keywords: Java

Thread group ThreadGroup identifies a collection of threads. Once a thread belongs to a thread group, the thread group it belongs to cannot be replaced.

The advantages of using thread group: convenient unified management, thread combination for copying, fast reading to a thread, unified setting, etc.

ThreadGroup does not belong to the content of Java Concurrent package, it is the content of java.lang.

Basic methods:

1. Get the current thread group name:

Thread.currentThread().getThreadGroup().getName();

Output main in the main method

2. Put threads into a thread group

ThreadGroup tg = new ThreadGroup("My Group");
MyThread2 thrd = new MyThread2(tg, "MyThread #1");
MyThread2 thrd2 = new MyThread2(tg, "MyThread #2");
MyThread2 thrd3 = new MyThread2(tg, "MyThread #3");

Where Thread and ThreadGroup related constructors:

public Thread(ThreadGroup group, Runnable target) {  
	init(group, target, "Thread-" + nextThreadNum(), 0);  
}  
  
  
public Thread(ThreadGroup group, String name) {  
	init(group, null, name, 0);  
}  
  
  
public Thread(ThreadGroup group, Runnable target, String name) {  
	init(group, target, name, 0);  
}  
  
public Thread(ThreadGroup group, Runnable target, String name,  long stackSize) {  
	init(group, target, name, stackSize);  
}  

They all end up calling the same function:

   private void init(ThreadGroup g, Runnable target, String name,  
                     long stackSize) {  
Thread parent = currentThread();  
SecurityManager security = System.getSecurityManager();  
if (g == null) {  
        //Security check  
    if (security != null) {  
    g = security.getThreadGroup();  
    }  
  
       //Set thread group  
    if (g == null) {  
    g = parent.getThreadGroup();  
    }  
}  
  
   //Check accessibility  
g.checkAccess();  
  
    //Do you have permission to access  
if (security != null) {  
    if (isCCLOverridden(getClass())) {  
        security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);  
    }  
}  
  
    //Add thread to thread group but not started  
    g.addUnstarted();  
  
this.group = g;  
this.daemon = parent.isDaemon();//Whether to guard threads  
this.priority = parent.getPriority();//priority  
this.name = name.toCharArray();  
if (security == null || isCCLOverridden(parent.getClass()))  
    this.contextClassLoader = parent.getContextClassLoader();  
else  
    this.contextClassLoader = parent.contextClassLoader;  
this.inheritedAccessControlContext = AccessController.getContext();  
this.target = target;  
setPriority(priority);  
       if (parent.inheritableThreadLocals != null)  
    this.inheritableThreadLocals =  
    ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);  
       this.stackSize = stackSize;  
       tid = nextThreadID();  
       this.me = this;  
   }  

3. Copy thread group:

Thread thrds[] = new Thread[tg.activeCount()];
tg.enumerate(thrds);

The activeCount here is obviously to get the active thread. Note. By default, replication occurs with its child thread groups.

4. Exception handling not caught

There is an uncaughtException() method in ThreadGroup. When an Unchecked exception occurs to a thread in a thread group, the execution environment calls this method for related processing. If necessary, you can redefine this method

Unified exception handling:

public class ThreadGroupExec {

    public static void main(String[] args) {
        ThreadGroup threadGroup1 = new ThreadGroup("group1"){
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println(t.getName() + ": " + e.getMessage());
            }
        };

        // It's anonymous
        Thread thread1 =
                // This thread is a member of threadGroup1
                new Thread(threadGroup1, new Runnable() {
                    @Override
                    public void run() {
                        // Throw unchecked exception
                        throw new RuntimeException("Test exception");
                    }
                });

        thread1.start();
    }
}

View constructor:

public class ThreadGroup implements Thread.UncaughtExceptionHandler {  
    private final ThreadGroup parent;//Father ThreadGroup  
    String name;//Name of ThreadGroupr  
    int maxPriority;//Thread maximum priority  
    boolean destroyed;//Destroyed or not  
    boolean daemon;//Whether to guard threads  
    boolean vmAllowSuspension;//Can I interrupt  
  
    int nUnstartedThreads = 0;//Threads not started yet  
    int nthreads;//Number of threads in ThreadGroup  
    Thread threads[];//Threads in ThreadGroup  
  
    int ngroups;//Number of thread groups  
    ThreadGroup groups[];//Thread group array  

Reference resources:

https://blog.csdn.net/evankaka/article/details/51627380

http://blog.csdn.net/edward_qing_lee/article/details/8767612

https://www.cnblogs.com/yiwangzhibujian/p/6212104.html

Posted by besbajah on Tue, 31 Mar 2020 08:24:13 -0700