多线程条件下使用SimpleDateFormat报错:java.lang.NumberFormatException: multiple points、empty String、For input

多线程条件下使用SimpleDateFormat报错:java.lang.NumberFormatException: multiple points、empty String、For input,第1张

错误详情

       使用时间格式转换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

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/799047.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-06
下一篇2022-05-06

发表评论

登录后才能评论

评论列表(0条)

    保存