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());
    }
}
上一篇:核心知识-ThreadLocal介绍+经典应用场景


下一篇:AndroidStudio_安卓原生开发_Android中在LinearLayout中控制按钮居中---Android原生开发工作笔记137