多线程映射工具——ThreadLocal

ThreadLocal相当于一个Map<Thread, T>,各线程使用自己的线程对象Thread.currentThread()作为键存取数据,但ThreadLocal实际上是一个包装了这个Map,并且线程只能存取自己的数据,不能操作其它线程的数据。

  • T get()
  • set(T)
  • remove()
  • # T initialValue()

代码示例:

public static void main(String[] args) {
String[] names = new String[]{"A", "B", "C", "D", "E"};
for(int i=0; i<names.length; i++){
final String myName = names[i];
new Thread(){
public void run(){
name.set(myName);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
test();
}
}.start();
} /*
运行结果:
Thread-0 -> 我的名字叫A
Thread-2 -> 我的名字叫C
Thread-1 -> 我的名字叫B
Thread-3 -> 我的名字叫D
Thread-4 -> 我的名字叫E
*/
} private static ThreadLocal<String> name = new ThreadLocal<String>(); public static void test(){
System.out.println(Thread.currentThread().getName() + " -> 我的名字叫" + name.get());
}
上一篇:DownloadProvider源码解析——与Volley对比


下一篇:Components of the Impala Server