package thread.local; public class Test { // 线程局部变量:初始值默认是null private final static InheritableThreadLocal<String> basicholder = new InheritableThreadLocal<String>(); // 存放的是引用 private final static InheritableThreadLocal<StringBuilder> referHolder = new InheritableThreadLocal<StringBuilder>(); public static void main(String[] args) throws Exception { basicholder.set("parent initial value"); referHolder.set(new StringBuilder("reference")); Thread a = new Thread() { public void run() { for (int i = 0; i < 2; i++) { // 子线程能够获得父线程的值 System.out.println("child-thread-begin=" + basicholder.get()); System.out.println("child-thread-begin2=" + referHolder.get()); try { Thread.sleep(200); } catch (InterruptedException e) { } } } }; a.start(); Thread.sleep(100); basicholder.set("parent reset this value"); referHolder.get().append(" new value"); System.out.println("end=" + basicholder.get()); System.out.println("end=" + referHolder.get()); } }
执行结果:
child-thread-begin=parent initial value
child-thread-begin2=reference
end=parent reset this value
end=reference new value
child-thread-begin=parent initial value
child-thread-begin2=reference new value
创建子线程的时候,子线程会继承InheritableThreadLocal中父线程此刻的值,但是只会在创建的时候继承一次。如果在子线程的生命周期内,父线程修改了自己的线程局部变量值,子线程再次读取,获取的仍然是第一次读取的值。即:子线程继承父线程的值,只是在线程创建的时候继承一次。之后子线程与后父线程便相互独立。
相关推荐
多线程访问同一个共享变量时,容易出现并发冲突,为了保证线程的安全,一般使用者在访问共享变量时,需要进行适量的同步。而ThreadLocal提供了线程的私有变量,每个线程都可以通过set()和get()来对这个私有变量进行...
主要为大家详细介绍了java多线程编程之InheritableThreadLocal,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
Android 详解ThreadLocal及InheritableThreadLocal 概要: 因为在android中经常用到... 在最初使用Threadlocal的时候,很容易会产生的误解就是threadlocal就是一个线程。 首先来看下Threadlocal的简单例子:
:pushpin: TransmittableThreadLocal(TTL) :pushpin: ...但对于使用线程池等会池化线程化的执行组件的情况,线程由线程池创建好,并且线程是池化起来反复使用的;这时父子线程关系的ThreadLocal值传
NULL 博文链接:https://jnh.iteye.com/blog/2000288
InheritableThreadLocal跟ThreadLocal差不多,关键点在Thread#init方法中会对Thread中的实例变量inheritableThreadLocals进行赋值操作,将父线程的本地变量复制到子线程中 首先通过ServiceLoader.load方法生成一个...
... 5. InheritableThreadLocal作用和实现方式 ?...9. HashMap为什么线程不安全 10. HashMap在jdk7和8中的区别 11. HashMap 为啥将链表改成红黑树? 12. ConcurrentHashMap在jdk7和8中的区别? ...