标签:
引自:http://ifeve.com/threadlocal%e4%bd%bf%e7%94%a8/
ThreadLocal的官方API解释为:
“该类提供了线程局部 (thread-local) 变量。这些变量不同于它们的普通对应物,因为访问某个变量(通过其 get 或 set 方法)的每个线程都有自己的局部变量,它独立于变量的初始化副本。ThreadLocal 实例通常是类中的 private static 字段,它们希望将状态与某一个线程(例如,用户 ID 或事务 ID)相关联。”
大概的意思有两点:
public class TreadLocalTest {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final ThreadLocal<HashMap> threadLocal = new ThreadLocal<HashMap>() {
@Override
protected HashMap initialValue() {
System.out.println(Thread.currentThread().getName()
+ "initialValue");
return new HashMap();
}
};
public static class T1 implements Runnable {
// private final static Map map = new HashMap();
private int id;
public T1(int id) {
this.id = id;
}
public void run() {
Map map = threadLocal.get();
Random random = new Random();
for (int i = 0; i < 6; i++) {
int a = random.nextInt(5);
map.put(i, i + id * 100 + a);
System.out
.println(Thread.currentThread().getName() + " i:" + i
+ " a:" + a + " time:" + sdf.format(new Date()) + map);
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() +
" i:" + i
+ " a:" + a +
" time:" + sdf.format(new Date()) + " value:"
+ map.get(i) + map);
} catch (Exception ex) {
}
}
System.out.println(Thread.currentThread().getName()
+ "# map.size()=" + map.size() + " # " + map);
}
}
public static void main(String[] args) {
Thread[] runs = new Thread[4];
T1 t = new T1(1);
for (int i = 0; i < runs.length; i++) {
runs[i] = new Thread(t);
}
for (int i = 0; i < runs.length; i++) {
runs[i].start();
}
}
}
标签:
原文地址:http://www.cnblogs.com/fanguangdexiaoyuer/p/5339443.html