一直说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时出现异常,异常原因是:得到的字符串不一致。
解决方案:
- 线程加锁
- 每个线程创建一个SimpleDateFormate对象
- 不想这么麻烦,就直接使用新的时间工具类LocalDate和LocalTime