线程组和优先级

线程组

Java 用 ThreadGroup 类 来表示线程组。

每个线程都属于一个线程组,如果创建线程没有显式指定,会继承父线程的线程组。

ThreadGroup 是一个树形结构,可以包含其他线程或线程组。

public class ThreadGroupTest {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            printThreadGroup(Thread.currentThread());
        });
        thread.start();
        thread.join();
        printThreadGroup(Thread.currentThread());
    }

    public static void printThreadGroup(Thread currentThread) {
        System.out.println("threadName:" + currentThread.getName());
        System.out.println("threadGroupName:" + currentThread.getThreadGroup().getName());
    }
}

输出

threadName:Thread-0
threadGroupName:main
threadName:main
threadGroupName:main

常用方法

  • 获取线程组名称
Thread.currentThread().getThreadGroup().getName()
  • 线程组复制
// 获取当前的线程组
ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
// 复制一个线程组到一个线程数组(获取Thread信息)
Thread[] threads = new Thread[threadGroup.activeCount()];
threadGroup.enumerate(threads);
  • 线程组异常 统一处理

继承 ThreadGroup 并重写 uncaughtException 方法

优先级

给线程或线程组指定一个优先级,范围是1-10,设置优先级是给操作系统参考,实际执行还是不确定的。

Thread实例通过 setPriority设置优先级

线程组 ThreadGroup实例通过setMaxPriority设置最大优先级,就是如果线程的优先级不能超过所属线程组的最大优先级。

守护线程

当运行的线程都是守护线程时,JVM 会退出。换句话说,就是守护线程在没有其他线程运行时会自动关闭。

可以通过 Thread 实例的 setDaemon 设置守护线程。

有一种线程的目的就是无限循环,如果整个线程不结束,JVM也不会结束。那么谁来负责结束整个线程?

答案就是使用守护线程。当其他线程执行完毕后,JVM会自动退出,守护线程也就结束了。

例如,下面的方法会在 2000 毫秒后,输出 I'm main End,然后自动退出。

    public static void main(String[] args) throws InterruptedException {
        Thread daemonThread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(System.currentTimeMillis());
            }
        });
        daemonThread.setDaemon(true);
        daemonThread.start();

        System.out.println("I'm main");
        Thread.sleep(2000);
        System.out.println("I'm main End");
    }
Last Updated:
Contributors: mcs