Common methods and data structures of thread groups

Common methods of thread groups

1. Get the name of the current thread group

// 或者当前运行线程所属的线程组
Thread.currentThread().getThreadGroup().getName();

2. Copy thread group

// 复制一个线程数组到一个线程组
Thread[] threads = new Thread[2]; 
ThreadGroup threadGroup = new ThreadGroup("copyGroup");
threadGroup.enumerate(threads);

3. Thread group unified exception handling

public class ThreadGroupDemo{
    public static void main(String[] args){
        ThreadGroup threadGroup1 = new ThreadGroup("group1"){
            // 继承ThreadGroup并重新定义一下方法
            // 在【线程成员】抛出unchecked exception
            // 会执行次方法
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                super.uncaughtException(t, e);
                System.out.println(t.getName() + ": " + e.getMessage());
            }
        };
        // 这个线程是threadGroup1的一员
        Thread thread1 = new Thread(threadGroup1, new Runnable(){
            public void run(){
                // 模拟抛出异常    
                throw new RuntimeException("测试异常");
            }
        });
        
        thread1.start();
    }
}

 

 Thread group data structure

A thread group can also contain other thread groups, not just threads.

public class ThreadGroup implements Thread.UncaughtExceptionHandler {
    private final ThreadGroup parent; // 父亲ThreadGroup
    String name; // ThreadGroup的名称
    int maxPriority; // 线程最大优先级
    boolean destroyed; // 是否被销毁
    boolean daemon; // 是否守护线程
    boolean vmAllowSuspension; // 是否可以中断

    int nUnstartedThreads = 0; // 还未启动的线程
    int nthreads; // ThreadGroup中线程数目
    Thread threads[];  // ThreadGroup中的线程

    int ngroups; // 线程组数目
    ThreadGroup groups[]; // 线程组数组
}

// 私有构造函数
private ThreadGroup() {     // called from C code
   this.name = "system";
   this.maxPriority = Thread.MAX_PRIORITY;
   this.parent = null;
}

public ThreadGroup(String name) {
   // 
   this(Thread.currentThread().getThreadGroup(), name);
}

public ThreadGroup(ThreadGroup parent, String name) {
   this(checkParentAccess(parent), parent, name);
}

// 私有构造函数,主要的构造函数
private ThreadGroup(Void unused, ThreadGroup parent, String name) {
   this.name = name;
   this.maxPriority = parent.maxPriority;
   this.daemon = parent.daemon;
   this.vmAllowSuspension = parent.vmAllowSuspension;
   this.parent = parent;
   parent.add(this);
}

// 检查parent
private static Void checkParentAccess(ThreadGroup parent) {
   parent.checkAccess();
   return null;
}
// 判断当前运行的线程是否具有修改线程组的权限
public final void checkAccess() {
   // Java的安全管理器,它允许应用程序在执行一个可能不安全或敏感的操作前确定该操作时什么
   // 以及是否是在允许执行该操作的安全上下文中执行它。
   SecurityManager security = System.getSecurityManager();
   if (security != null) {
       security.checkAccess(this);
   }
}

In summary, the thread group is a tree structure, and each thread group can have multiple threads or thread groups. The thread group can play a unified role in controlling thread priority and checking thread permissions.

The difference between thread group and thread pool

Thread group [ the meaning of the existence of thread group, the first reason is safety ]

The threads created by Java by default belong to the system thread group, and the threads of the same thread group can modify each other's data. Different thread groups cannot modify data "cross-thread group" to ensure data security.

Thread pool [ efficiency ]

The creation and termination of threads require a certain amount of system time. Creating and deleting threads continuously will waste a lot of time. Therefore, create a thread and make it not end after executing the task, but put it into a sleep state, and wake it up when needed, then a certain amount of time can be saved. If you use the thread pool for management, ensure efficiency.

Common points:

  1. Manage a certain number of threads.
  2. All threads can be controlled-including sleep, wake up, end, create, and interrupt.

Guess you like

Origin blog.csdn.net/weixin_39443483/article/details/113049219