标签:内部类 单例 extends 信息 als xtend stat lin override
使用ThreadLocal创建的变量只能被当前线程访问,其他线程则无法访问和修改。
用法如下:
private void testThreadLocal() {
Thread t = new Thread() {
ThreadLocal<String> mStringThreadLocal = new ThreadLocal<>();
@Override
public void run() {
super.run();
mStringThreadLocal.set("localValue"); // 设置值
mStringThreadLocal.get(); // 获取值
}
};
t.start();
}
ThreadLocalMap
的对象ThreadLocalMap
对象不为空,则设置值;否则创建这个ThreadLocalMap
对象并设置值public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
下面是一个利用Thread对象作为句柄获取ThreadLocalMap对象的代码:
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
可以看出一个Thread
实例就有一个ThreadLocalMap
对象。
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
实际上ThreadLocal的值是放入了当前线程的一个ThreadLocalMap实例中,所以只能在本线程中访问,其他线程无法访问。
ThreadLocal的实例以及其值仍然存放在JVM的堆。
如果应用使用了线程池,那么之前的线程实例处理完之后,会再次被复用,所以ThreadLocal变量会一直存在。
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;
}
}
}
标签:内部类 单例 extends 信息 als xtend stat lin override
原文地址:http://www.cnblogs.com/byrhuangqiang/p/6338106.html