获取父线程 java_java子线程中获取父线程的threadLocal中的值
我們都知道線程本地變量表也就是ThreadLocal在我們做線程級(jí)的數(shù)據(jù)隔離時(shí)非常好用,但是有時(shí)候我們會(huì)想如何讓子線程獲取到父線程的ThreadLocal,其實(shí)在線程中除了ThreadLocal外還有InheritableThreadLocal,顧名思義,可繼承的線程變量表,可以讓子線程獲取到父線程中ThreadLocal的值。
public classBaseTest {public static final InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal<>();public static final ThreadLocal threadLocal = new ThreadLocal<>();public static voidmain(String[] args) {
inheritableThreadLocal.set("Inheritable hello");
threadLocal.set("hello");new Thread(()->{
System.out.println(String.format("子線程可繼承值:%s",inheritableThreadLocal.get()));
System.out.println(String.format("子線程值:%s",threadLocal.get()));new Thread(()->{
System.out.println(String.format("孫子線程可繼承值:%s",inheritableThreadLocal.get()));
System.out.println(String.format("孫子線程值:%s",threadLocal.get()));
}).start();
}).start();
}
執(zhí)行后獲取返回值。
可以看到不可繼承的ThreadLocal子線程是不能共享父線程的??衫^承的ThreadLocal如何實(shí)現(xiàn)呢?
其原理和ThreadLocal基本上一致,都是線程中存有ThreadLocalMap
/*ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class.*/ThreadLocal.ThreadLocalMap threadLocals= null;/** InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.*/ThreadLocal.ThreadLocalMap inheritableThreadLocals= null;
我們?cè)趎ew線程時(shí)init方法會(huì)有如下操作。
Thread parent =currentThread();
../省略代碼if (inheritThreadLocals && parent.inheritableThreadLocals != null)this.inheritableThreadLocals =ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
如果允許new的線程繼承當(dāng)前線程的threadlocalMap,那么new的線程會(huì)copy一份當(dāng)前線程也就是父線程的inheritableThreadLocals 。這兒也可以說明繼承有兩條件,new的線程允許繼承(默認(rèn)允許),父線程的inheritableThreadLocals 不為null。
**這兒要注意不管是創(chuàng)建ThreadLocal還是inheritableThreadLocals(如果父線程沒有) 的ThreadLocalMap都是在Threadlocal.set方法的時(shí)候創(chuàng)建的,即懶加載。
public voidset(T value) {
Thread t=Thread.currentThread();
ThreadLocalMap map=getMap(t);if (map != null)
map.set(this, value);elsecreateMap(t, value);
}
總結(jié)
以上是生活随笔為你收集整理的获取父线程 java_java子线程中获取父线程的threadLocal中的值的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 超硬不锈钢成特斯拉Cybertruck生
- 下一篇: yum java 1.7_centos通