ThreadLocal的实际作用及实现原理

在多线程的情况下,我们有时需要访问同一个共享变量,并且对共享变量做某种操作。但是由于多线程的存在,不同线程间对同一个共享变量的操作可能会互相影响。可是在实际业务中,我们可能都需要对共享变量做初始操作,又不想互相影响,这个时候就需要一个机制,将多线程之间相互隔离。从而使得其他线程对该共享变量进行操作时,不会影响其他线程。

例如以下代码,我们希望各个线程都对初始变量count做加10操作。如果使用多线程,代码如下:

public class ThreadLocalWork extends Thread {
    private static int count = 0;

    @Override
    public void run() {
        //每个线程都对count的初始值做加10操作
        count += 10;
        System.out.println("当前线程为:" + Thread.currentThread().getName() + "count:" + count);
    }


    public static void main(String[] args) {
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(new ThreadLocalWork(), "thread--" + i);
        }
        for (Thread thread : threads) {
            thread.start();
        }

    }
}

结果如下:

当前线程为:thread--1count:20
当前线程为:thread--0count:10
当前线程为:thread--4count:30
当前线程为:thread--2count:40
当前线程为:thread--3count:50

如果我们希望,每一个线程进来,count的初始值都是0,上面的代码显然不符合要求。

public class ThreadLocalTask {
    private final static ThreadLocal<Integer> local = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    public static void main(String[] args) {
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(() -> {
                int count = local.get();
                count += 10;
                local.set(count);
                System.out.println("当前的线程:" + Thread.currentThread().getName() + "--->" + count);
            }, "thread--" + i);
        }
        for (Thread thread : threads) {
            thread.start();
        }
    }

}

运行结果:

当前的线程:thread--1--->10
当前的线程:thread--4--->10
当前的线程:thread--0--->10
当前的线程:thread--2--->10
当前的线程:thread--3--->10

ThreadLocal源码分析

从上面的代码可以看出,ThreadLocal是实现线程安全的一种手段。但是ThreadLocal为什么能够做到线程隔离?我们直接从源码中寻找答案。

get()方法
//ThreadLocal中内部维护着一个map
hreadLocal.ThreadLocalMap threadLocals = null
    public T get() {
    	//获得当前线程
        Thread t = Thread.currentThread();
        //获得维护的map,首次访问为空
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
    private T setInitialValue() {
    //因为我们在代码中重写了这个方法,所以value得到我们定义的初始值
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
        	//直接给当前线程t中的map进行赋值,定义的初始值为value,创造一个map
            createMap(t, value);
        return value;
    }
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
        ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
        	//生成一个大小为16的map
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }
set(T)方法
    public void set(T value) {
        Thread t = Thread.currentThread();
        //获取当前map
        ThreadLocalMap map = getMap(t);
        //此时map不为空
        if (map != null)
        	//重新设置map值
            map.set(this, value);
        else
            createMap(t, value);
    }
结论

ThreadLocal之所以能够实现线程间隔离,是因为其内部为每一个线程创建了一个属于本线程的一个ThreadLocalMap,这个map记录了初始值。所以当每个线程取值的时候,是从自己的map中取值,赋值也是如此。所以线程间的操作互不影响,相互隔离。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值