ThreadLocal原理

原理

ThreadLocal原理_第1张图片
可以清楚的看到,尽管看上去value是调用ThreadLcoal对象的set(value)方法,但是实际上value还是保存在线程自己的threadLocals属性中的。因此当然是每个线程自己单独持有一份,各线程直接互不影响了。

使用


/**
 * @author FANG
 * @version 1.8
 * @coding UTF-8
 * @date 2020/8/22 19:17
 */
public class ThreadLocalTest1 extends Thread {
     
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    //也不能通过静态代码块初始化
    static {
     
        threadLocal.set(0);
    }

    /**
     *
     */
    public ThreadLocalTest1() {
     
        //不能在构造函数中初始化
//        threadLocal.set(0);
//        System.out.println(threadLocal.get());
    }

    private void initLocal() {
     
        threadLocal.set(0);
    }

    public Integer nextInt() {
     
//        System.out.println(threadLocal.get());
        if (threadLocal.get() != null) {
     
            threadLocal.set(threadLocal.get() + 1);
        } else {
     
            initLocal();
        }
        return threadLocal.get();
    }

    /**
     *
     */
    @Override
    public void run() {
     
        super.run();
//        System.out.println("run=" + threadLocal.get());
//        initLocal();
        for (int i = 0; i < 10; i++) {
     
//            System.out.println("run=" + threadLocal.get());
            System.out.println(getName() + "==" + nextInt());
        }
    }

    public static void main(String[] args) {
     
//        System.out.println("0=" + ThreadLocalTest1.threadLocal.get());
        ThreadLocalTest1 threadLocalTest1 = new ThreadLocalTest1();
//        System.out.println(threadLocalTest1.nextInt());
//        System.out.println("1=" + ThreadLocalTest1.threadLocal.get());
//        threadLocalTest1.run();
        threadLocalTest1.start();
//        System.out.println("2=" + ThreadLocalTest1.threadLocal.get());
//
        ThreadLocalTest1 threadLocalTest2 = new ThreadLocalTest1();
        threadLocalTest2.start();
        ThreadLocalTest1 threadLocalTest3 = new ThreadLocalTest1();
        threadLocalTest3.start();
    }
}

你可能感兴趣的:(ThreadLocal原理)