SimpleDateFormat是是 Java 中一个非常常用的类,该类用来对日期字符串进行解析和格式化输出,但是DateFormat 和 SimpleDateFormat 类不都是线程安全的,在生产环境的多线程或高并发情况使用 format() 和 parse() 方法,会出现很多问题:
比如格式化后的时间跟期望格式化的时间不一致,或者出现一些其他的像Exception in thread “Thread-1” java.lang.NumberFormatException: multiple points的异常错误,为了解决这种问题可以在需要的时候创建新实例或者使用同步锁:
1、新建实例
public class DateUtils {
//整合日期转换
public static final DateFormat taobaoDF = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
public static final DateFormat normalDF = new SimpleDateFormat("yyyy-MM-dd");
/**
* 入参日期格式转换为系统默认的日期格式
*
* @param strTaobaoDate
* @return
* @throws Exception
*/
public static String format(String strTaobaoDate) throws Exception {
String strResult = "";
DateFormat normalDF = new SimpleDateFormat("yyyy-MM-dd");
DateFormat taobaoDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = taobaoDF.parse(strTaobaoDate);
strResult = normalDF.format(date);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(
"日期格式不正确,日期格式如下:yyyy-MM-dd HH:mm:ss 例:2014-01-01 00:00:00");
}
return strResult;
}
}
2、使用同步锁
public class DateUtils {
public static final DateFormat taobaoDF = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
public static final DateFormat normalDF = new SimpleDateFormat("yyyy-MM-dd");
/**
* 入参日期格式转换为系统默认的日期格式
*
* @param strTaobaoDate
* @return
* @throws Exception
*/
public static String format(String strTaobaoDate) throws Exception {
String strResult = "";
Date date = null;
try {
synchronized(taobaoDF){
date = taobaoDF.parse(strTaobaoDate);
}
synchronized(normalDF){
strResult = normalDF.format(date);
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception(
"日期格式不正确,日期格式如下:yyyy-MM-dd HH:mm:ss 例:2014-01-01 00:00:00");
}
return strResult;
}
网上还有一些其它解决方案与原因说明,可以看:https://www.cnblogs.com/zhuimengdeyuanyuan/archive/2017/10/25/7728009.html