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();
}
}
结果:
第二个小测试:
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"