package test; /** * 使用InheritableThreadLocal 将父线程中的Integer对象传给子线程 * @author xxzx * */ public class InheritableThreadLocalDemo { //final 可用volatile ,该对象的创建表示默认主线程创建了一条父线程 private static InheritableThreadLocal<Integer> intVal=new InheritableThreadLocal<Integer>(); public static void main(String [] args) { Runnable rp = () ->{ intVal.set(new Integer(10)); Runnable rc=()->{ Thread thd=Thread.currentThread(); String name=thd.getName(); System.out.println(name+" "+intVal.get()); }; Thread thdChild =new Thread(rc); thdChild.setName("child"); thdChild.start(); }; new Thread(rp).start(); } }
代码说明:由于存储在本地变量中的值都是不相关的。当一个新的线程被创建出来,它就会获得一个新的包含initialValue()值的存储槽。
InheritableThreadLocal是 ThreadLocal的子类,除了定义一个InheritableThreadLocal()的构造方法,这个类还声明了下面的peotect()方法
T childValue(T parentValue): 在子线程被创建出来的时候用父线程的值作为参数计算出子线程的初始值,此方法会在子线程启动之前被调用
InheritableThreadLocal类的源代码如下(为了查看方面已删去部分注释):
package java.lang; import java.lang.ref.*; public class InheritableThreadLocal<T> extends ThreadLocal<T> { protected T childValue(T parentValue) { return parentValue; } /** * Get the map associated with a ThreadLocal. * * @param t the current thread */ ThreadLocalMap getMap(Thread t) { return t.inheritableThreadLocals; } /** * Create the map associated with a ThreadLocal. * * @param t the current thread * @param firstValue value for the initial entry of the table. */ void createMap(Thread t, T firstValue) { t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue); } }