浅谈ThreadLocal

首先沿用API中的解释:

该类提供了线程局部 (thread-local) 变量。这些变量不同于它们的普通对应物,因为访问某个变量(通过其 getset 方法)的每个线程都有自己的局部变量,它独立于变量的初始化副本。ThreadLocal 实例通常是类中的 private static 字段,它们希望将状态与某一个线程(例如,用户 ID 或事务 ID)相关联。 

我觉得这句话不太好理解,下面说下我的理解:

threadlocal它不是什么线程,它只是thread类中的一个变量,而且是隐式沿用的,我们写代码的时候是无法直接拿到的,这个类中只有4个方法,和一个无参的构造方法。它可以通过set和get方法来保存和获取thread中的一个对象,从而使线程之间在操作自己的对象时互不影响,也就是线程的隔离性好,给多线程的并发访问提供了一个新的思路。比如以下代码:

public class ThreadLocalTest1 {
	static ThreadLocal<Integer> threadlocal = new ThreadLocal<Integer>();
	public static void main(String[] args) {
		
		for (int i = 0; i < 2; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					int data = new Random().nextInt();
					threadlocal.set(data);
					System.out.println(Thread.currentThread()
							+ "put data " + data);
					new A().get();
					new B().get();

				}
			}).start();

		}

	}

	static class A {
		int data = threadlocal.get();
		public void get() {
			System.out.println("A "+Thread.currentThread().getName()
					+ "get data " + threadlocal.get());

		}

	}

	static class B {

		int data = threadlocal.get();
		public void get() {
			System.out.println("B "+Thread.currentThread().getName()
					+ "get data " + threadlocal.get());

		}
	}

}
代码中的两个线程操作data数据是互不影响。

现在来看下threadlocal的set()方法

 public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
 /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

上面的是threadlocal的源码,下面的是thread中的源码。threadlocal是thread的一个局部变量吧,

  /**
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     * @param map the map to store.
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

如果map是空的就用creatmap方法来给map赋值。
通过源码分析:

1,在map中的key是this,也就是threadlocal,所以多次调用set方法最后只会保存最后一个值,存在覆盖。

2,threadlocalmap是threadlocal中的一个内部类,它提供给thread一个map,最后给threadlocal来保存thread中的变量的副本,它的关键字是threadlocal;




如果有什么地方不对的,望各给大神不吝赐教哈




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值