好久没有记录了,今天来记录下工作中的一些细节问题。

工作中经常用到SimpleDateFormat,但是大部分人可能都会按照下面的格式去使用

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

上面的方式在我们看来一般是不会出现什么问题,如果出现在多线程的情况下,它就会有问题。因为SimpleDateFormat是线程不安全的类。如果要保证SimpleDateFormat线程的安全性就要使用下面的方式使用:

public class DateUtils { private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){ @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyy-MM-dd"); } }; public static void main(String[] args) { DateFormat dateFormat = df.get(); dateFormat.format(new Date()); System.out.println(dateFormat); } }

这里使用static修饰ThreadLocal对象,主要是让所有此类实例共享此静态变量,也就是说在类第一次被使用时装载,只分配一块存储空间,所有此类的对象都可以操控这个变量。