欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

InheritableThreadLocal sample code

程序员文章站 2022-07-14 12:45:42
...

The following code print null. If using InheritableThreadLocal, it print main.

 

 

class A {
  //static ThreadLocal local = new InheritableThreadLocal();
  static ThreadLocal local = new ThreadLocal();
}

public class Sample {
  public static void main (String [] args) {
    A.local.set("main");    
    Thread t = new Thread() {
      @Override
      public void run() {
        System.out.println(A.local.get());  
      }
    };
    t.start();
  }  
}

  The following code shows the usage of childValue method.

 

class A {
  static ThreadLocal<String> local = new InheritableThreadLocal<String>() {
    @Override
    protected String childValue(String parentValue) {
      return "child: " + parentValue;
    }
  };
}

public class Sample {
  public static void main (String [] args) {
    A.local.set("main");    
    Thread t = new Thread() {
      @Override
      public void run() {
        System.out.println(A.local.get());  
      }
    };
    t.start();
  }  
}
 

 

相关标签: thread