Java.lang InheritableThreadLocal

1 Java.lang InheritableThreadLocal介绍

java.lang.InheritableThreadLocal 类扩展了ThreadLocal从父线程提供的值来继承子线程:创建一个子线程的时候,子的所有可继承线程局部变量可以是其父有接收值的初始值。

2 Java.lang InheritableThreadLocal声明

public class InheritableThreadLocal<T>
   extends ThreadLocal<T>

3 Java.lang InheritableThreadLocal方法

方法 描述
protected T childValue(T parentValue)  此方法计算,子类在这个可继承线程局部变量的父级的值在创建子线程时函数的初始值。

4 Java.lang InheritableThreadLocal案例

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
// Java program to illustrate inheritance of customized value 
// from parent thread to child thread 
  
class ParentThread extends Thread { 
    // anonymous inner class  for overriding childValue method. 
    public static InheritableThreadLocal gfg_tl = new InheritableThreadLocal() { 
        public Object childValue(Object parentValue) 
        { 
            return "child data"; 
        } 
    }; 
    public void run() 
    { 
        // setting the new value 
        gfg_tl.set("parent data"); 
        // parent data 
        System.out.println("Parent Thread Value :" + gfg_tl.get()); 
  
        ChildThread gfg_ct = new ChildThread(); 
        gfg_ct.start(); 
    } 
} 
class ChildThread extends Thread { 
  
    public void run() 
    { 
        // child data 
        System.out.println("Child Thread Value :" + ParentThread.gfg_tl.get()); 
    } 
} 
class ThreadLocalDemo { 
  
    public static void main(String[] args) 
    { 
        ParentThread gfg_pt = new ParentThread(); 
        gfg_pt.start(); 
    } 
} 

输出结果为:

Parent Thread Value:parent data 
Child Thread Value:child data

 

热门文章

优秀文章