ThreadLocal用于实现线程内部的数据共享,对于同一个线程来说,使用ThreadLocal获取的存储对象是同一个;不同的线程使用ThreadLocal会从不同的内存区域中获取存储对象,也就是ThreadLocal会针对当前线程开辟一块独立的存储空间。ThreadLocal存储Integer如下:
public class ThreadLocalTest {
public ThreadLocal threadLocal = new ThreadLocal();
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{ public ThreadLocal() { } }
ThreadLocal存储的对象是泛型化对象,在构造ThreadLocal对象时指定存储的对象的具体类型:
ThreadLocaltl = new ThreadLocal ()
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);
}
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 {
static class Entry extends WeakReference> {
Object value;
Entry(ThreadLocal> k, Object v) {
super(k);
value = v;
}
}
private static final int INITIAL_CAPACITY = 16;
private Entry[] table;
private int size = 0;
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 {
//每个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 sThreadLocal = new ThreadLocal();
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));
}
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对象。



