我的基于 ThreadLocal 的类有问题。任何帮助,将不胜感激。这是一个带有简单列表的基类:
public class ThreadLocalTest {
protected static final ThreadLocal<List<String>> thList = new ThreadLocal<List<String>>() {
protected List<String> initialValue() {
return new ArrayList<String>();
}
};
public static void put(String k) {
thList.get().add(k);
}
public static List<String> getList() {
return thList.get();
}
}
我正在以这种方式对其进行测试:
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("------------------thread1---------------------------");
ThreadLocalTest.put("a");
ThreadLocalTest.put("b");
List<String> l = ThreadLocalTest.getList();
System.out.println(l.size());
System.out.println("----------------------------------------------------");
}
});
Thread th2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("------------------thread2---------------------------");
ThreadLocalTest.put("c");
List<String> l = ThreadLocalTest.getList();
System.out.println(l.size());
System.out.println("----------------------------------------------------");
}
});
th1.run();
th2.run();
th1.run();
th2.run();
th1.run();
th2.run();
th1.run();
th2.run();
所以我得到的是:
------------------thread1---------------------------
2
----------------------------------------------------
------------------thread2---------------------------
3
----------------------------------------------------
------------------thread1---------------------------
5
----------------------------------------------------
------------------thread2---------------------------
6
----------------------------------------------------
------------------thread1---------------------------
8
----------------------------------------------------
------------------thread2---------------------------
9
----------------------------------------------------
------------------thread1---------------------------
11
----------------------------------------------------
------------------thread2---------------------------
12
----------------------------------------------------
您会看到这些线程似乎实际上共享相同的列表,但我不明白为什么。
有小费吗?