InheritableThreadLocal

public class TestThreadLocal {

    // 使用ThreadLocal 子线程获取不到父线程的值
//    public static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    // 使用InheritableThreadLocal 子线程可以获取父线程的值
    /**
     * @see Thread#init(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, java.security.AccessControlContext, boolean)
     * @see InheritableThreadLocal#childValue(java.lang.Object)
     * @see ThreadLocal.ThreadLocalMap#ThreadLocalMap(java.lang.ThreadLocal.ThreadLocalMap)
     */
    public static InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();

    public static void main(String...args){
        threadLocal.set("Hello");

        Thread thread = new Thread(()->System.out.println("thread:" + threadLocal.get()));
        thread.start();

        System.out.println("main:" + threadLocal.get());
    }
}

InheritableThreadLocal

上一篇:MOOC数据结构PTA-04-树6 Complete Binary Search Tree


下一篇:PSD位置传感器