先看个例子
主线程和子线程都对 类成员变量u进行修改,两者的修改都会影响主线程的输出u,最后结果可能是2也可能是3
public class Test {
private static Integer u = 1;
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
u++;
// local.set(1000);
// System.out.println(local.get());
}
});
t.start();
u++;
//local.set(1);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(u);
//System.out.println(local.get());
}
如果两个线程都对ThreadLocal中的变量进行修改,则发现两线程的修改互不影响,主线程输出的永远是1,子线程永远是1000
public class Test {
private static Integer u = 1;
private static ThreadLocal local = new ThreadLocal() {
@Override
protected Integer initialValue() {
return 100;
}
};
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// u++;
local.set(1000);
System.out.println(local.get());
}
});
t.start();
//u++;
local.set(1);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(u);
System.out.println(local.get());
}
即每个线程可以独立的维护自己的副本,其他线程不会影响。
类成员变量local明明是一个对象,为什么两个线程对其修改 互补影响呢?
看一下ThreadLocal的源码,set方法,先得到一个ThreadLocalMap,这个ThreadLocalMap是被维护在当前线程currentThread的成员变量上,,如果t为null就执行创建方法,ThreadLocalMap其实是ThreadLocal的内部类,里面靠entry维护key和value,key是ThreadLocal对象,value是你要放的对象。
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;
}
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;
}
}
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);
}
}
public
class Thread implements Runnable {
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
}
而ThreadLocal.get方法就是从当前线程的ThreadLocalMap中得到以线程副本为key的value值。
public T get() {
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();
}
总结,执行线程副本set方法,ThreadLocal.set(T) 表面上多个线程用的其实是一个线程副本,其实set进去的对象是维护在当前线程中的,当前线程有个成员变量map,只不过map的key是线程副本
弱引用问题
ThreadLocal弱引用问题。结论:弱引用是为了防止内存泄露,即使不调用threadlocal.remove,只要threadlocal过了作用域,为null,那因为Entry是弱引用(threadlocal在Entry的WeakReference为变量),所以threadlocal就能在下次垃圾回收时回收。而Entry的value值,在下次调用set get remove方法会进行回收。
具体看以下文章