ThreadLocal,从表面上读英文的意思为线程本地变量,这样也许更好理解了,就是每一个线程本身独有的,不与其它线程共享的变量。
经常使用的就这几个,俩内部类,四个方法。java
举例:数据库
定义两个不一样任务的线程,分别向各自的本地变量中存放值,见证两个线程本地变量中的内容是互不干扰的。ide
public class MyThreadLocal { // 采用匿名内部类的方式来重写initialValue方法 private static final ThreadLocal<Object> threadLocal = new ThreadLocal<Object>() { /** * ThreadLocal没有被当前线程赋值时或当前线程刚调用remove方法后调用get方法,返回此方法值 */ @Override protected Object initialValue() { System.out.println("调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!"); return null; } }; // 操纵int类型的任务线程 public static class MyIntegerTask implements Runnable { private String name; MyIntegerTask(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { // ThreadLocal.get方法获取线程变量 if (null == MyThreadLocal.threadLocal.get()) { // ThreadLocal.et方法设置线程变量 MyThreadLocal.threadLocal.set(0); System.out.println("线程" + name + ": 0"); } else { int num = (Integer) MyThreadLocal.threadLocal.get(); MyThreadLocal.threadLocal.set(num + 1); System.out.println("线程" + name + ": " + MyThreadLocal.threadLocal.get()); if (i == 3) { MyThreadLocal.threadLocal.remove(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } // 操纵string类型的任务线程 public static class MyStringTask implements Runnable { private String name; MyStringTask(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { if (null == MyThreadLocal.threadLocal.get()) { MyThreadLocal.threadLocal.set("a"); System.out.println("线程" + name + ": a"); } else { String str = (String) MyThreadLocal.threadLocal.get(); MyThreadLocal.threadLocal.set(str + "a"); System.out.println("线程" + name + ": " + MyThreadLocal.threadLocal.get()); } try { Thread.sleep(800); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { new Thread(new MyIntegerTask("IntegerTask1")).start(); new Thread(new MyStringTask("StringTask1")).start(); } }
运行结果:
调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值! 线程IntegerTask1: 0 调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值! 线程StringTask1: a 线程StringTask1: aa 线程IntegerTask1: 1 线程StringTask1: aaa 线程IntegerTask1: 2 线程StringTask1: aaaa 线程IntegerTask1: 3 线程StringTask1: aaaaa 调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值! 线程IntegerTask1: 0
涉及到的源码:性能
get();方法:供ThreadLocal对象来调用测试
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(); }
getMap();方法:这个方法是返回当前线程t中的一个成员变量threadLocals,它是Thread类中的一个内部类this
ThreadLocal.ThreadLocalMap threadLocals = null; ThreadLocalMap getMap(Thread t) { return t.threadLocals; }
看一下ThreadLocalMap的实现:能够看到ThreadLocalMap的Entry继承了WeakReference(弱引用类),而且使用ThreadLocal做为键值。spa
static class ThreadLocalMap { static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } } 。。。。。。。。。 }
getEntry();方法线程
private Entry getEntry(ThreadLocal<?> key) { int i = key.threadLocalHashCode & (table.length - 1); Entry e = table[i]; if (e != null && e.get() == key) return e; else return getEntryAfterMiss(key, i, e); }
setInitialValue();方法:就是若是map不为空,就设置键值对,为空,再建立Mapcode
private T setInitialValue() { T value = initialValue(); Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); return value; }
createMap();方法:若是map为空,就初始化ThreadLocalMap对象
void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
不难看出,get()方法,首先获取当前的线程,而后经过getMap(t)方法获取到一个map,map的类型为ThreadLocalMap。而后接着下面获取到<key,value>键值对,若是获取成功,则返回value值,若是map为空,则调用setInitialValue方法返回value。
测试完上面的例子,看完get方法的实现,应该明白ThreadLocal是怎么个原理了,大体以下(就是这样的):首先,在每一个线程Thread内部有一个ThreadLocal.ThreadLocalMap类型的成员变量threadLocals,这个threadLocals就是用来存储实际的变量的,键值为当前ThreadLocal变量,value为变量(好比说上面定义的String变量或者Integer变量)。初始时,在Thread里面,threadLocals为空,当经过ThreadLocal变量调用get()方法或者set()方法,就会对Thread类中的threadLocals进行初始化,而且以当前ThreadLocal变量为键值,以ThreadLocal要保存的变量为value,存到threadLocals。若是要使用副本变量,就能够经过get方法在threadLocals里面查找。
这种存储结构的好处:
最多见的ThreadLocal使用场景为 用来解决 数据库链接、Session管理等。
好比如下,代码来自:https://www.iteye.com/topic/1...
private static final ThreadLocal threadSession = new ThreadLocal(); public static Session getSession() throws InfrastructureException { Session s = (Session) threadSession.get(); try { if (s == null) { s = getSessionFactory().openSession(); threadSession.set(s); } } catch (HibernateException ex) { throw new InfrastructureException(ex); } return s; }
通常有两种方法: