import java.util.concurrent.locks.LockSupport; /** * 功能描述: * * @Author: lishq * @Date: 2021/12/9 9:42 */ public class ThreadTest { public static InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal(); public static void main(String[] args) throws InterruptedException { threadLocal.set("thread created before"); Thread thread = new Thread(new Runnable() { public void run() { System.out.println("子线程获取初始值:"+threadLocal.get()); LockSupport.park(); System.out.println("子线程获取修改后的值:"+threadLocal.get()); } }); thread.start(); Thread.sleep(1000L); System.out.println("父线程重新赋值"); threadLocal.set("thread created after"); LockSupport.unpark(thread); System.out.println("父线程获取修改后的值:"+threadLocal.get()); } }
原理
InheritableThreadLocal 实现父子线程数据通信。子线程创建的时候,拷贝了父线程的值。正因为如此,所以在子线程初始化后,在修改了父线程的值,子线程却无法获得修改后的值。