一、为什么线程不安全
SimpleDateFormat被定义为static,那么多个线程共用,就会导致线程不安全,但是SimpleDateFormat被声明局部变量,一个线程使用一个SimpleDateFormat就不会导致线程不安全
二、如何线程才安全,推荐使用ThreadLocal
package com.example.dateTest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 线程安全写法
*
* @Author lmx
*/
public class ThreadLocalDateUtil {
private static final String date_format = "yyyy-MM-dd HH:mm:ss";
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
public static DateFormat getDateFormat() {
DateFormat df = threadLocal.get();
if (df == null) {
df = new SimpleDateFormat(date_format);
threadLocal.set(df);
}
return df;
}
public static String formatDate(Date date){
String result = "";
try {
result = getDateFormat().format(date);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static Date parse(String strDate){
Date resultDate = null;
try {
resultDate = getDateFormat().parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return resultDate;
}
}
三、学习threadLocal很有意思
threadLocal用来多线程隔离数据,很有意思的一个知识点,可以学习下。