ThreadLocal用在线程中存储线程的变量,每个线程被创建都会有自己的ThreadLocal对象,ThreadLocal对其他线程是不可见的,各个线程维护自己的ThreadLocal变量。
ThreadLocal内部有一个ThreadLocalMap的内部类,其中的Entry存储了当前线程的数据。
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;
}
}
......
}
entry的key就是当前线程,,ThreadLocal和synchronized的区别主要在于synchronized用于控制访问共享变量,ThreadLocal则是维护自己线程的变量。
ThreadLocal主要的方法有