多线程操作SimpleDateFormat出现异常

一直说SimpleDateFormate有线程不安全的问题,我测试了一下

package com.test0802.p;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: zyx
 * @Date: 2020/8/2 11:00
 * @Decription:
 */
public class Test01 {

    // @description: zyx 2020/8/2 11:02:
    public static void main(String agrs[]) {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i=0;i<10;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SimpleDemo simpleDemo=new SimpleDemo(simpleDateFormat);
                    try {
                        System.out.println(simpleDemo.getDate("2020-02-02 01:01:00"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

    }

    static class SimpleDemo{
        SimpleDateFormat simpleDateFormat=null;
        SimpleDemo(SimpleDateFormat simpleDateFormat){
            this.simpleDateFormat=simpleDateFormat;
        }

        public String getDate(String date) throws ParseException {
            Date parse = simpleDateFormat.parse(date);
            String format = simpleDateFormat.format(parse);
            return format;
        }
    }
}

具体异常信息(多运行几次,会有不同结果的):
Exception in thread “Thread-2” Exception in thread “Thread-5” Exception in thread “Thread-1” Exception in thread “Thread-8” Exception in thread “Thread-6” Exception in thread “Thread-7” Exception in thread “Thread-0” Exception in thread “Thread-3” Exception in thread “Thread-4” java.lang.NumberFormatException: For input string: “E.2201E2”
2020-02-02 01:01:00
java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: For input string: “E.2201”
java.lang.NumberFormatException: For input string: “E022240”
java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: For input string: “”
at com.test0802.p.Test01$SimpleDemo.getDate(Test01.java:40)
at com.test0802.p.Test01$1.run(Test01.java:23)
第40行代码就是
Date parse = simpleDateFormat.parse(date);

在多线程操作同一个SimpleDateFormate时出现异常,异常原因是:得到的字符串不一致。

解决方案:

  1. 线程加锁
  2. 每个线程创建一个SimpleDateFormate对象
  3. 不想这么麻烦,就直接使用新的时间工具类LocalDate和LocalTime
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值