当在变量中维护的每线程属性(例如,用户 ID、事务 ID)必须自动传输到任何创建的子线程时,可优先使用可继承的线程局部变量而不是普通的线程局部变量。
测试代码
private static ThreadLocal tl = new ThreadLocal<>();
private static ThreadLocal tlInherit = new InheritableThreadLocal<>();
public static void main(String[] args) throws Exception {
log.info("1threadName:{},tl = {}, tlInherit = {}", Thread.currentThread().getName(), tl.get(), tlInherit.get());
tl.set(Record.builder().id(3333L).build());
tlInherit.set(Record.builder().id(3333L).build());
log.info("2threadName:{},tl = {}, tlInherit = {}", Thread.currentThread().getName(), tl.get(), tlInherit.get());
new Thread(() -> {
Record record2 = Optional.ofNullable((Record)tl.get()).orElse(new Record());
Record record2Inherit = Optional.ofNullable((Record)tlInherit.get()).orElse(new Record());
record2.setId(2222L);
record2Inherit.setId(2222L);
log.info("3threadName:{},tl = {}, tlInherit = {}", Thread.currentThread().getName(), tl.get(), tlInherit.get());
}).start();
//保证下面fc执行一定在上面异步代码之后执行
Thread.sleep(500);
log.info("4threadName:{},tl = {}, tlInherit = {}", Thread.currentThread().getName(), tl.get(), tlInherit.get());
}
运行结果
InheritableThreadLocal继承了ThreadLocal,重写了三个方法(childValue、getMap、createMap)。
源码:
childValue
当创建子线程时,子线程继承了父线程的局部变量。 通常情况下父子线程的值相同,可以通过childValue方法,可以将子项的值设为父项。
getMap
createMap