從ThreadLocal的名字上能夠看到,這是一個線程局部變量,也就是說,只有當前線程能夠訪問,既然是隻有當前線程能夠訪問的數據,天然是線程安全的.
public class ThreadLocalDemo {
private static ThreadLocal<SimpleDateFormat> t1 = new ThreadLocal<>();
public static class ParseDate implements Runnable {
int i = 0;
public ParseDate(int i) {
this.i = i;
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
try {
if (t1.get() == null)
t1.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
Date t = t1.get().parse("2015-03-29 19:29:" + i % 60);
System.out.println(i + ":" + t);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
es.execute(new ParseDate(i));
}
}
}
從這裏也能夠看到,爲每個線程人手分配一個對象工做並非有ThreadLocal來完成的.而是須要在應用層面保證的,若是在應用上爲每個線程分配了相同的對象實例,那麼ThreadLocal也不能保證線程安全,