public class App
{
public static void main(String[] args)
{
ThreadLocal<String> threadLocal = new ThreadLocal<String>();
threadLocal.set("String1");
threadLocal.set("String2");
threadLocal.set("String3");
System.out.println("==============");
System.out.println("++ " + threadLocal.get());
System.out.println("++ " + threadLocal.get());
}
}
the output is
=============
++ String3
++ String3
請參閱源代碼中的set方法,對於指定的Thread,它的threadlocalmap只能容納一個map條目?如示例所示,map.set(this,value);這裏「this」是var「threadLocal」,所以「String3」將覆蓋之前的值。 我誤會嗎?ThreadLocal源代碼混亂
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);// here "this" is the var "threadLocal"
else
createMap(t, value);
}
是,'ThreadLocal'只能在同一時間有一個值。 – shmosel
您也可以以澄清你的疑問和看到「設置(T值)」的方法定義閱讀「ThreadLocal的」文檔。 https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html –