源代码:
import java.text.SimpleDateFormat;
import java.util.Date;
public class ThreadLocalTest {
private static final ThreadLocal<SimpleDateFormat> sdf1 = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yy-MM-dd HH:mm:ss");
}
};
private static final SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
public static void main(String[] args) throws InterruptedException {
finalTest();
System.out.println(sdf.format(new Date()));
Thread.sleep(1000);
System.out.println("--------------------------------------");
threadLocalTest();
System.out.println(sdf1.get().format(new Date()));
}
private static void finalTest() {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(sdf.format(new Date(new Date().getTime() - 1000000000)));
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(sdf.format(new Date(new Date().getTime() + 1000000000)));
}
});
thread2.start();
}
private static void threadLocalTest() {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(sdf1.get().format(new Date(new Date().getTime() - 1000000000)));
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(sdf1.get().format(new Date(new Date().getTime() + 1000000000)));
}
});
thread2.start();
}
}
测试结果:
18-07-31 16:53:09
18-08-12 06:39:49
18-07-31 16:53:09
--------------------------------------
18-07-20 03:06:30
18-07-31 16:53:10
18-08-12 06:39:50
使用static SimpleDateFormat,输出的日期有两个是相同的,可以看出线程不安全;
使用ThreadLocal的每一个时间都是正确的。
如果是jdk是8及以上的,直接使用java.time下的LocalDateTime即可