InheritableThreadLocal

时间:2023-03-10 03:07:11
InheritableThreadLocal

InheritableThreadLocal继承自ThreadLocal,但比ThreadLocal多一个特性:

子线程可以继承父亲线程上下文中的信息

但是,有两个点需要注意的:

  • 只有子线程创建之前的内容可以被继承,子线程创建之后,父子线程的上线文之间就是独立的了
  • 父子线程的上线文都需要独立清理

示例代码如下:

public class InheritableThreadLocalTest {

    public static void main(String[] args) throws InterruptedException {
final ThreadLocal<String> caches = new InheritableThreadLocal<String>();
caches.set("1111"); System.out.println("caches from parent thread " + caches.get()); new Thread(new Runnable() { @Override
public void run() {
// Inheritable from parent thread
System.out.println("caches in sub thread " + caches.get()); try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} // 父线程修改了值,子线程看不到
System.out.println("caches in sub thread " + caches.get()); caches.set("2222");
}
}).start(); Thread.sleep(1000);
caches.set(null);
System.out.println("caches from parent thread " + caches.get());
Thread.sleep(3000);
// 子线程修改了值,父线程同样也看不到
System.out.println("caches from parent thread " + caches.get());
} }