ThreadLocal源码浅析

ThreadLocal为解决多线程程序的并发问题提供了一种新的思路。使用这个工具类可以很简洁地编写出优美的多线程程序,ThreadLocal并不是一个Thread,而是Thread的局部变量

先上一个小demo:

public class ThreadLocalDemo {
   public static ThreadLocal<Integer> integerThreadLocal = new ThreadLocal<>();
   public static void main(String[] args) {
      Thread thread1 = new Thread(new ThreadTest());
      Thread thread2 = new Thread(new ThreadTest());
      Thread thread3 = new Thread(new ThreadTest());
      thread1.start();
      thread2.start();
      thread3.start();

   }


   static class ThreadTest implements Runnable {
      private  int count = 0;

      @Override
      public void run() {
         for (int i = 0; i < 3; i++) {
            count ++;
            integerThreadLocal.set(count);
            System.out.println("线程名:" + Thread.currentThread().getName() + ";值是:" + integerThreadLocal.get());
         }
      }
   }
}

运行结果

线程名:Thread-1;值是:1
线程名:Thread-2;值是:1
线程名:Thread-0;值是:1
线程名:Thread-0;值是:2
线程名:Thread-0;值是:3
线程名:Thread-2;值是:2
线程名:Thread-1;值是:2
线程名:Thread-2;值是:3
线程名:Thread-1;值是:3

发现静态的Threadlocal里面保存的变量并没有因为多线程的修改而覆盖,实际上是依存于当前线程;废话不多说看看Threadlocal的关键方法:

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}
    
void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
    table = new Entry[INITIAL_CAPACITY];
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    setThreshold(INITIAL_CAPACITY);
}
     我们可以看到 存储值用的是ThreadLocalMap,在第一次创建的时候是把线程作为key,要保存的变量值做value保存进去的,ThreadLocal用于保存某个线程共享变量:对于同一个static ThreadLocal,不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值