ThreadLocal应用与实现
什么是ThreadLocal以及如何使用
ThreadLocal 直译过来就是线程本地变量的意思。它是一个容器类,可以存入其他对象类型。
它的作用就是控制多个线程对同一个ThreadLocal变量读取和写入时,可以做到相互独立,互不影响。并且对多次get()操作返回的值是同一个。
ThreadLocal有两种初始化方式:
- 使用ThreadLocal的set(Object)方法设置初始值。
- 重写initialValues()方法,返回初始值。当调用get()方法获取值时,如果发现没有用set(Object)设置过值,则会调用initialValues()获取初始值。
示例代码如下:
//方式1
//在主线程中创建一个ThreadLocal变量,并初始化为1
ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
threadLocal.set(1);
//那么在主线程可以获得该值: value = 1
Integer value = threadLocal.get();
//在子线程中无法获取该值: valueChild = null
Integer valueChild = threadLocal.get();
//方式2
//在主线程通过复写initialValue()初始化ThreadLocal
AtomicInteger nextId = new AtomicInteger(0);
ThreadLocal<Integer> threadLocal2 = new ThreadLocal<Integer>() {
@override
protected Integer initialValue() {
return nextId.getAndInrement();
}
};
//在子线程第一次调用get()方法时会回调initialValue()获得初始值,并且多次调用不变
Integer id = threadLocal2.get();
源码实现
ThreadLocal实现线程变量隔离的核心在于get()方法,那么接下来通过get()方法的源码追踪其实现原理。
public T get() {
//获取当前调用线程对象
Thread t = Thread.currentThread();
//根据线程对象获取其关联的Threa