最近微信群里有个网友分享了他做京东的过程,给大家分享一道面试题。京东端:子线程怎么获取父线程ThreadLocal的值.测试代码如下:publicstaticvoidmain(String[]args)throwsInterruptedException{ThreadparentParent=newThread(()->{ThreadLocalthreadLocal=newThreadLocal<>();threadLocal.set(1);InheritableThreadLocalinheritableThreadLocal=newInheritableThreadLocal<>();inheritableThreadLocal.set(2);newThread(()->{System.out.println("threadLocal="+threadLocal.get());System.out.println("inheritableThreadLocal="+inheritableThreadLocal.get());}).start();},"父线程");parentParent.start();}运行结果如下:子线程在父线程中获取ThreadLocal中的值。另外上周抽空整理了一份简历,里面不仅有简历写作要点,还有几位大佬的简历模板。感兴趣的就来这里领取吧!原理如下:首先我们要知道Thread类维护了两张ThreadLocalMap图片跟进。newThread()方法在其构造方法中调用了init方法。init方法将inheritThreadLocals的值设置为true,继续跟进图片。程序员专属壁纸,关注公众号SpringForAll社区,回复:壁纸,即可获取无水印高清壁纸。当inheritThreadLocals的值为true且父线程的inheritableThreadLocals不为null时,将父线程的inheritableThreadLocals赋值给当前线程的inheritableThreadLocals。这是子线程获取父线程ThreadLocal值的关键。推荐:上周抽空整理了一份简历,里面不仅包括了简历写作的要点,还包括了几个大咖的简历模板。感兴趣的就来这里领取吧!继续跟进,看看InheritableThreadLocal的get()方法。get()方法没什么好看的,就是ThreadLocal的get()方法。图片注:InheritableThreadLocal重写了ThreadLocal的getMap()方法ThreadLocalMapgetMap(Threadt){//获取线程自身的变量threadLocals,绑定到当前调用线程的成员变量threadLocals上returnt.threadLocals;}voidcreateMap(Threadt,TfirstValue){t.threadLocals=newThreadLocalMap(this,firstValue);//创建ThreadLocalMap的table属性并赋值,将firstValue放在数组的最前面。}createMap方法不仅创建了threadLocals,还将要添加的局部变量的值添加到threadLocals中。InheritableThreadLocal类继承了ThreadLocal类,并重写了childValue、getMap、createMap方法。当调用createMap方法时,它会创建inheritableThreadLocal而不是threadLocals。同理,当前调用线程调用get方法时,getMap方法返回的不是threadLocals,而是inheritableThreadLocal。