`
aty
  • 浏览: 35530 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

InheritableThreadLocal使用(二)只在子线程创建的时候,继承一次

阅读更多
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中父线程此刻的值,但是只会在创建的时候继承一次。如果在子线程的生命周期内,父线程修改了自己的线程局部变量值,子线程再次读取,获取的仍然是第一次读取的值。即:子线程继承父线程的值,只是在线程创建的时候继承一次。之后子线程与后父线程便相互独立。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics