线程组概念

1. 概述

线程组(ThreadGroup),其作用是对线程进行批量管理。

每个线程便然存在于一个线程组中,线程不能独立于线程组存在。

main() 方法的线程名为 main。
需要注意的是,如果在创建新线程时没有显式设置线程组,那么默认将父线程的线程组设置为自己的线程组。

public class Strings {
    public static void main(String[] args) {
        System.out.printf("main() name: %s %n", Thread.currentThread().getName());
        Thread t1 = new Thread();
        System.out.printf("t1 thread name: %s %n", t1.getName());
        System.out.printf("t1 thread group: %s %n", t1.getThreadGroup().getName());
    }
}

// main() name: main 
// t1 thread name: Thread-0 
// t1 thread group: main 

线程组是向下引用的树形结构,因为如果下级引用上级会导致 GC 无法回收上级线程。


2. 线程优先级问题

在概述中,我们知道线程必然存在于一个线程组中。

那么当线程和线程组的优先级不一致时会导致什么样的结果呢?

public class Strings {
    public static void main(String[] args) {
        ThreadGroup tg = new ThreadGroup("thread group");
        tg.setMaxPriority(5);
        Thread t = new Thread(tg, "thread 1");
        t.setPriority(9);
        System.out.printf("thread group priority: %d %n", tg.getMaxPriority());
        System.out.printf("thread 1 priority: %d %n", t.getPriority());
    }
}

// thread group priority: 5 
// thread 1 priority: 5

所以,线程的优先级大于所在线程组的优先级,那么该线程的优先级将会失效,取而代之的是线程组的最大优先级。


3. 常用操作

3.1 统一异常处理

public class Strings {
    public static void main(String[] args) {
        ThreadGroup tg = new ThreadGroup("thread group") {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.err.printf("thread name: %s, error message %s; %n", t.getName(), e.getMessage());
            }
        };

        Runnable task = () -> {
            throw new RuntimeException("thread runtime exception.");
        };
        Thread t1 = new Thread(tg, task, "thread 1");
        t1.start();
    }
}
// thread name: thread 1, error message thread runtime exception.; 

3.2 拷贝线程组

Thread[] threads = new Thread[threadGroup.activeCount()];
TheadGroup threadGroup = new ThreadGroup();
threadGroup.enumerate(threads);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值