ThreadLocal用于实现线程内部的数据共享,对于同一个线程来说,使用ThreadLocal获取的存储对象是同一个;不同的线程使用ThreadLocal会从不同的内存区域中获取存储对象,也就是ThreadLocal会针对当前线程开辟一块独立的存储空间。ThreadLocal存储Integer如下:
public class ThreadLocalTest {
/*定义一个全局变量 来存放线程需要的变量*/
public ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
public void test {
/*创建两个线程*/
for(int i=0; i<2;i++){
new Thread(new Runnable() {
@Override
public void run() {
Integer value = new Integer();
threadLocal.set(value);
threadLocal.get();
//操作
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadLocal.remove();
}
}).start();
}
}
}
创建ThreadLocal对象:
//注意泛型
public class ThreadLocal<T> {
/**
* Creates a thread local variable.
* @see #withInitial(java.util.function.Supplier)
*/
public ThreadLocal() {
}
}
ThreadLocal存储的对象是泛型化对象,在构造ThreadLocal对象时指定存储的对象的具体类型:
ThreadLocal<Integer> tl = new ThreadLocal<Integer>()
ThreadLocal存储对象 - set方法
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//很关键,此处传入this,thread和ThreadLocalMap一一对象,多个ThreadLocalMap绑定同一个ThreadLocal
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
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
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);
}
}
Thread中的threadLocals对象:
public class Thread implements Runnable {
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
//每个Thread中都有一个ThreadLocalMap,ThreadLocalMap中存储了ThreadLocal和需要存储的对象
ThreadLocal.ThreadLocalMap threadLocals = null;
}
由set(T value)源码可见,每个Thread中都有一个ThreadLocalMap,而ThreadLocalMap绑定了ThreadLocal和需要存储的对象,也就是同一个ThreadLocal对象为不同的线程各自开辟了一块存储空间,每个线程只访问自己存储空间中的对象。
ThreadLocal读取对象 - get
public T get() {
Thread t = Thread.currentThread();
//从当前线程中获取ThreadLocalMap
ThreadLocalMap map = getMap(t);
//从ThreadLocalMap中获取存储的值
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
get方法会从当前线程中获取ThreadLocalMap对象,而ThreadLocalMap中存储了数据值。
ThreadLocal删除对象-remove
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
从当前线程中获取ThreadLocalMap对象,从ThreadLocalMap中删除。
Android中每个线程中只能有一个looper对象,就是靠ThreadLocal来实现的:
public final class Looper {
private static final String TAG = "Looper";
// sThreadLocal.get() will return null unless you've called prepare().
@UnsupportedAppUsage
//用于为不同的线程保存不同的looper对象
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
1、sThreadLocal对象
sThreadLocal用static final修饰,所以Android中的所有的Looper对象都是靠sThreadLocal这个对象存储。
2、prepare方法
sThreadLocal.get()用于获取当前线程中的Looper对象,如果已经存在的话,抛出运行时异常。如果当前线程中不存在Looper对象,创建Looper对象,并用sThreadLocal存储。
3、myLooper()方法
用于获取当前线程中的Looper对象,通过sThreadLocal获取当前线程中的ThreadLocalMap中存储的Looper对象。
4、创建MessageQueue
在Looper的构造方法中创建MessageQueue对象,因为对于每一个线程来说,Looper的构造方法只能执行一次,因此一个线程只能有一个Looper对象、一个Looper对象只能有一个MessageQueue对象。