SimpleDateFormat是线程不安全的类,一般不建议定义为static变量,因为在多线程操作时会出现线程不安全问题,进而导致相关的问题
解决方案:
使用ThreadLocal进行操作
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 考虑到SimpleDateFormat为线程不安全对象,故应用ThreadLocal来解决,
* 使SimpleDateFormat从独享变量变成单个线程变量
*/
public class DateFormatUtils {
//写法1:
private static ThreadLocal<SimpleDateFormat> threadLocal1 = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static Date parseByOne(String dateStr) throws ParseException {
return threadLocal1.get().parse(dateStr);
}
public static String format(Date date) {
return threadLocal1.get().format(date);
}
//写法2:
private static final String date_format = "yyyy-MM-dd HH:mm:ss";
private static ThreadLocal<SimpleDateFormat> threadLocal2 = new ThreadLocal<SimpleDateFormat>();
public static SimpleDateFormat getDateFormat() {
SimpleDateFormat sdf = threadLocal2.get();
if (sdf == null) {
sdf = new SimpleDateFormat(date_format);
threadLocal2.set(sdf);
}
return sdf;
}
public static String formatDate(Date date) throws ParseException {
return getDateFormat().format(date);
}
public static Date parseByTwo(String strDate) throws ParseException {
return getDateFormat().parse(strDate);
}
}