转载:https://mp.weixin.qq.com/s?__biz=MzkxNjQxODg1Mw==&mid=2247487427&idx=1&sn=035245fc459973c8be698d67ecf42d9c&chksm=c1517789f626fe9fe40f09e2bd96ff9cd82f86e875621f72c577650ece158160db2b5978c9c0&scene=132&exptype=timeline_recommend_article_extendread_samebiz#wechat_redirect
public class ThreadLocalDemo {
private static Map<String, String> map = new HashMap<>();
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
int finalI = i;
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ",value实际赋值为:" +finalI + "");
//map变量赋值
map.put("key", finalI + "");
getValue();
}).start();
}
}
public static void getValue() {
String value = map.get("key");
System.out.println(Thread.currentThread().getName() + ",getValue获取值为:" + value + "");
}
}
public class ThreadLocalDemo2 {
private static ThreadLocal<Map<String, String>> map = new ThreadLocal<>();
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
int finalI = i;
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ",value实际赋值为:" + finalI + "");
//map变量赋值
Map<String, String> stringMap = map.get();
if (stringMap == null) {
stringMap = new HashMap<>();
map.set(stringMap);
}
stringMap.put("key", finalI + "");
getValue();
}).start();
}
}
public static void getValue() {
if (map.get() == null) {
return;
}
String value = map.get().get("key");
System.out.println(Thread.currentThread().getName() + ",getValue获取值为:" + value + "");
}
}
public class ThreadLocalDemo3 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
int finalI = i;
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ",value实际赋值为:" +finalI + "");
//map变量赋值
Map<String, String> map = new HashMap<>();
map.put("key", finalI + "");
getValue(map);
}).start();
}
}
public static void getValue(Map<String, String> map) {
String value = map.get("key");
System.out.println(Thread.currentThread().getName() + ",getValue获取值为:" + 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);
}
}
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
//略。。。
}
tab[i] = new Entry(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) {
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
int i = key.threadLocalHashCode & (table.length - 1);