线程篇——Thread类源码

Thread类源码


Thread类重要属性

​ 我们跟到Thread类,看下线程有哪些属性。

​ Thread类的重要属性:

	/* For autonumbering anonymous threads. */
    private static int threadInitNumber;
     /* Whether or not the thread is a daemon thread. */
    private boolean     daemon = false;
    private int            priority;

​ 先看下Thread构造方法的参数:

Thread(ThreadGroup group, Runnable target, String name, long stackSize)

继续往下跟,构造方法是调用了init,init共有这几个参数:

init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc,
                  boolean inheritThreadLocals) 

以下解释摘自源码init方法注释:

线程组 g – the Thread group

要执行的Runnable实现类 target – the object whose run() method gets called

线程名称 name – the name of the new Thread
期望的堆栈大小 stackSize – the desired stack size for the new thread, or zero to indicate that this parameter is to be ignored.
权限控制上下文 acc – the AccessControlContext to inherit, or AccessController.getContext() if null
是否继承threadLocal inheritThreadLocals – if true, inherit initial values for inheritable thread-locals from the constructing thread

共这几个主要的属性:

属性 作用
threadInitNumber(线程id) 线程id,用于标识不同的线程
name(线程名称) 线程名称,如果不传入就使用默认的格式设置。用于标识不同的线程、debug
daemon(是否是守护线程) true代表是守护线程,默认false,用户线程
priority 优先级,这个属性是想告诉线程调度器,用户希望哪些线程可以相对多运行
inheritThreadLocals(是否继承ThreadLocal的初始值) 默认是true,通过这个属性可以实现日志的链路追踪

关于inheritThreadLocals的两个测试:

public class ThreadLocalTest {
    ThreadLocal<String> userName = new ThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return "Admin User";
        }
    };

    @Test
    public void threadLocalTest() throws InterruptedException {
        System.out.println("我是主线程的userName:" + userName.get());
        Thread thread = new Thread(() -> System.out.println("我是子线程的userName:" + userName.get()));
        thread.start();
        thread.join();
    }
}

结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IPOkGKgO-1636864770687)(image-20211111171111282.png)]

第二个小测试:

public class ThreadLocalTest {
   
    ThreadLocal<String> userName = new ThreadLocal<String>() {
   
        @Override
        protected String initialValue() {
   
            return "Admin User";
        }
    };

    @Test
    public void threadLocalTest() throws InterruptedException {
   
        userName.set("Main User"
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值