---
title: "InheritableThreadLocal的使用"
author: "aty"
date: "2013-08-05T19:43:04Z"
tags: []
categories: ["编程语言"]
slug: "inheritablethreadlocal"
draft: false
lastmod: "2013-08-05T19:43:04Z"
id: 1920610
url: "https://aty.iteye.com/blog/1920610"
---

JDK提供了InheritableThreadLocal类，用来让子线程继承父线程的值。在创建子线程的时候，子线程会接收此刻父线程线程局部变量的初始值。

```
package thread.local;

public class Test
{
    // 线程局部变量:初始值默认是null
    private final static InheritableThreadLocal<String> parentholder = new InheritableThreadLocal<String>();

    // 线程局部变量:初始值默认是null
    private final static ThreadLocal<String> selfholder = new ThreadLocal<String>();

    public static void main(String[] args) throws Exception
    {
        parentholder.set("parent initial value");
        selfholder.set("parent initial value");

        Thread a = new Thread()
        {
            public void run()
            {
                // 子线程能够获得父线程的值
                System.out.println("child-thread-begin=" + parentholder.get());

                // 子线程获取的是自己的初值
                System.out.println("self child-thread-begin=" + selfholder.get());

            }
        };

        a.start();

        Thread.sleep(100);
    }
}
```