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());
    }
}
posted @ 2021-08-14 10:20  fly_bk  阅读(94)  评论(0编辑  收藏  举报