ThreadLocal这个类提供线程局部变量。 这些变量与其正常的对应方式不同,因为访问一个的每个线程(通过其get或set方法)都有自己独立初始化的变量副本。
举例说明:
public class ThreadLocalTest {
public static void main(String[] args) {
ThreadLocal<Object> threadLocal = new ThreadLocal<>();
Thread threadA = new Thread(() -> {
threadLocal.set("AAAAAAAA");
System.out.println(threadLocal + " 线程" + Thread.currentThread().getName() + " 线程值" + threadLocal.get());
}, "A");
threadA.start();
Thread threadB = new Thread(() -> {
threadLocal.set("BBBBBBB");
System.out.println(threadLocal + " 线程" + Thread.currentThread().getName() + " 线程值" + threadLocal.get());
}, "B");
threadB.start();
Thread threadC = new Thread(() -> {
threadLocal.set("CCCCCCC");
System.out.println(threadLocal + " 线程" + Thread.currentThread().getName() + " 线程值" + threadLocal.get());
}, "C");
threadC.start();
}
}
输出结果:
说明:代码中的threadLocal是公共的,也就是一个threadLocal对象,多个线程调用了其set方法,在各个线程中调用get方法,结果都是正确的,并没有因为多次操作一个公共的资源类(threadLocal)而导致数据混乱。
模拟一个非ThreadLocal的类的情况:
public class ThreadLocalTest2 {
public static void main(String[] args) {
UserTest user = new UserTest();
//创建3个线程
Thread threadA = new Thread(() -> {
user.setName("张无忌");
System.out.println(user + " 张无忌线程" + Thread.currentThread().getName() + " 线程值" + user.getName());
}, "A");
threadA.start();
Thread threadB = new Thread(() -> {
user.setName("张三丰");
//在B线程执行完 user.setName("张三丰")后,等待2秒,释放cpu资源
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(user + " 张三丰线程" + Thread.currentThread().getName() + " 线程值" + user.getName());
}, "B");
threadB.start();
Thread threadC = new Thread(() -> {
user.setName("杨过");
try {
//在C线程执行完user.setName("杨过") 操作之后,切换到B线程,
// 由于B之前已经执行了 user.setName("张三丰");C线程又将值改为了杨过,所以B线程获取的肯定是杨过
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(user + " 杨过线程" + Thread.currentThread().getName() + " 线程值" + user.getName());
}, "C");
threadC.start();
}
}
看看输出结果:
当然,我上面那个threadLocal的例子没有调用join,没有让出线程执行权,可能难以服众,所以我们将之前的代码修改一下:
public class ThreadLocalTest {
public static void main(String[] args) {
ThreadLocal<Object> threadLocal = new ThreadLocal<>();
Thread threadA = new Thread(() -> {
threadLocal.set("AAAAAAAA");
System.out.println(threadLocal + " 线程" + Thread.currentThread().getName() + " 线程值" + threadLocal.get());
}, "A");
threadA.start();
Thread threadB = new Thread(() -> {
threadLocal.set("BBBBBBB");
try {
//为了让线程B在线程C之后执行
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadLocal + " 线程" + Thread.currentThread().getName() + " 线程值" + threadLocal.get());
}, "B");
threadB.start();
Thread threadC = new Thread(() -> {
threadLocal.set("CCCCCCC");
try {
//让出线程C的cpu时间给线程B,等待线程B执行完之后 线程C再执行
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadLocal + " 线程" + Thread.currentThread().getName() + " 线程值" + threadLocal.get());
}, "C");
threadC.start();
}
}
分析:
先看threadLocal的set方法源码:
public void set(T value) {
//获取当前线程
Thread t = Thread.currentThread();
//获取线程的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null)
//this(key)就是一个ThreadLocal的实例
map.set(this, value);
else
createMap(t, value);
}
看看getMap方法:
ThreadLocalMap getMap(Thread t) {
//在Thread的源码中有这么一个属性: ThreadLocal.ThreadLocalMap threadLocals = null;
return t.threadLocals;
}
看看ThreadLocalMap这个类:
在ThreadLocal类中,有个静态内部类ThreadLocalMap,可以联想我们的hashMap,ThreadLocalMap是真正存储数据的地方
static class ThreadLocalMap {
//弱引用
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
//key是一个threadLocal对象
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table.
*/
private int size = 0;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
}
看看get方法:
public T get() {
//通过当前线程 获取当前线程的ThreadLocalMap,每个线程维护这一个ThreadLocalMap(可以看作是一个hashmap),通过this(ThreadLocal的一个实例)获取一个Entry,通过entry获取value
Thread t = Thread.currentThread();
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();
}
总结:每个线程维护这一个ThreadLocalMap,这是真正存放数据的地方,该map的key是一个ThreadLocal的实例,通过key获取对应的value。
You had me at hello ——胡小宝