该类提供了线程局部 (thread-local) 变量。这些变量不同于它们的普通对应物,因为访问某个变量(通过其 get 或 set 方法)的每个线程都有自己的局部变量,它独立于变量的初始化副本。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;
如果有什么地方不对的,望各给大神不吝赐教哈