为了彻底搞明白ThreadLocal的工作原理,下面会截取代码和画图详细说明.
简单ThreadLocal工作流程
- 首先搞清楚
Thread,ThreadLocal,ThreadLocalMap这三个类的关系.
1 | |
1 | |
上面两段代码截取jdk8源码,Thread对象内部定义了成员变量ThreadLocal.ThreadLocalMap threadLocals = null,ThreadLocalMap为ThreadLocal的一个静态内部类,三者的代码关系就这么简单.

假定在业务系统中有这样两个service和对应的方法方法.
- XService1
1
2
3
4
5
6
7
8public class XService1 { ThreadLocal<String> threadLocal1 = new ThreadLocal<String>(); public void testThreadLocalValue() { threadLocal1.set("test1"); String str1 = threadLocal1.get(); } } -
XService2 ``` public class XService2 { ThreadLocal
threadLocal2 = new ThreadLocal (); @Test public void testThreadLocalValue() { threadLocal2.set(“test2”); String str2 = threadLocal2.get(); }
}
1 | |
//n为当前table有效元素的个数 private boolean cleanSomeSlots(int i, int n) { boolean removed = false; Entry[] tab = table; int len = tab.length; do { //nextIndex方法能够保证从i到i-1遍历整个table i = nextIndex(i, len); Entry e = tab[i];
1 | |
1 | |