
使用时间格式转换SimpleDateFormat方法的时候,用static修饰,并在处于多线程的情况下执行,结果出现各种报错信息
public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Date parse(String stringDate) throws ParseException {
return sdf.parse(stringDate);
}
报错信息一
Exception in thread "1" Exception in thread "0" java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: multiple points
Exception in thread "0" Exception in thread "2" Exception in thread "1" java.lang.NumberFormatException: For input string: "255.E2552E"
java.lang.NumberFormatException: empty String
错误分析SimpleDateFormat中的日期格式不是同步的。SimpleDateFormat 是线程不安全的类,一般不要定义为 static 变量,如果定义为 static,必须加锁,或者使用 DateUtils 工具类。
解决方法方法1:加锁 (但是性能不太好,不推荐)
public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static synchronized Date parse02(String stringDate) throws ParseException {
return sdf.parse(stringDate);
}
方法2:ThreadLocal(为每个线程创建独立的格式实例,推荐)记得使用后remove
public static final ThreadLocal sdfThreadLocal = ThreadLocal.withInitial(()->new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
public static Date parseThreadLocal(String stringDate) throws ParseException {
return sdfThreadLocal.get().parse(stringDate);
}
另:阿里Java开发手册中推荐,在jdk8中用DateTimeFormatter 代替 SimpleDateFormat
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)