---
title: "InheritableThreadLocal使用（二）只在子线程创建的时候,继承一次"
author: "aty"
date: "2013-08-05T20:12:51Z"
tags: []
categories: ["编程语言"]
slug: "inheritablethreadlocal"
draft: false
lastmod: "2013-08-05T20:12:51Z"
id: 1920619
url: "https://aty.iteye.com/blog/1920619"
---

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