其他分享
首页 > 其他分享> > 10.ThreadLocal

10.ThreadLocal

作者:互联网

/**
 * 如果你创建了 一个 ThreadLocal 变量,那么访问这个变量的每个线程都会有这个变量的一个本地副本。
 * 当多个线程操作这个变量时,实际操作的是自己本地内存里面的变量,从而避免了线程安全问题
 */
public class ThreadLocalDemo {
    static ThreadLocal<String> local = new ThreadLocal<>();
    static void print(String s){
        System.out.println(s+":"+local.get());
        local.remove();
    }
    public static void main(String[] args){
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                local.set("threadA");
                print("threadA");
                System.out.println("threadA remove after:"+ local.get());
            }
        });
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                local.set("threadB");
                print("threadB");
                System.out.println("threadB remove after:"+ local.get());
            }
        });
        threadA.start();
        threadB.start();
        //threadB:threadB
        //threadA:threadA
        //threadB remove after:threadB
        //threadA remove after:threadA

        //执行local.remove();
        //threadA:threadA
        //threadB:threadB
        //threadA remove after:null
        //threadB remove after:null
    }
}
public class ThreadLocalDemo2 {
    static ThreadLocal<String> local = new ThreadLocal<>();
    public static void main(String[] args){
        local.set("hello");
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread:"+local.get());
            }
        });
        threadA.start();
        System.out.println("main:"+local.get());
        //thread:null
        //main:hello
        //同一个 ThreadLocal 变量在父线程中被设置值后, 在子线程中是获取不到的。
        //因为在子线程 threadA 里面调用 get 方法时当前线程 为 threadA 线程,而这里调用 set 方法设置线程变量的是 main 线程,
        // 两者是不同的线程,自然子线程访问时返回 null
    }
}
/**
 * InheritableThreadLocal
 * 子线程获取父线程的threadlocal变量
 */
public class ThreadLocalDemo3 {
    static ThreadLocal<String> local = new InheritableThreadLocal<>();
    public static void main(String[] args){
        local.set("hello");
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread:"+local.get());
            }
        });
        threadA.start();
        System.out.println("main:"+local.get());
        //main:hello
        //thread:hello
        //当父线程创建子线程时,构造函数会把父线程中 inheritableThreadLocals 变量里面的本地变量复制一份保存到子线程的 inheritableThreadLocals 变量里面
    }
}

标签:10,threadB,threadA,ThreadLocal,线程,new,local,public
来源: https://www.cnblogs.com/fly-book/p/11367548.html