1.概述
在平时的工作中,我们经常需要将日期在String和Date之间做转化,此时需要使用SimpleDateFormat类。使用SimpleDateFormat类的parse方法,可以将满足格式要求的字符串转换成Date对象;使用SimpleDateFormat类的format方法,可以将Date类型的对象转换成一定格式的字符串!但是有一点需要特别注意,SimpleDateFormat并非是线程安全的,也就是说在并发环境下,如果考虑不周使用SimpleDateFormat方法可以会出现线程安全方面的问题
2. 线程安全案例
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;/*** Created on 2018/11/03.*/
public class DateUtil {private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public static String formatDate(Date date)throws ParseException {return sdf.format(date);}public static Date parse(String strDate) throws ParseException{return sdf.parse(strDate);}
}
2.1 测试类
import java.text.ParseException;/*** Created on 2018/11/03.*/
public class DateUtilTest {public static class SimpleDateFormatThread extends Thread {private String dateStr;public SimpleDateFormatThread(String dateStr){this.dateStr = dateStr;}@Overridepublic void run() {try {System.out.println(this.getName()+":"+DateUtil.parse(dateStr));} catch (ParseException e) {e.printStackTrace();}}}public static void main(String[] args) {String dateStr = "2018-11-03 10:02:47";for(int i = 0; i < 5; i++){new SimpleDateFormatThread(dateStr).start();}}
}
2.2.运行结果:
Thread-4:Sat Nov 03 10:02:47 CST 2018
Thread-0:Sat Nov 03 10:02:47 CST 2018
java.lang.NumberFormatException: multiple pointsat sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)at java.lang.Double.parseDouble(Double.java:538)at java.text.DigitList.getDouble(DigitList.java:169)at java.text.DecimalFormat.parse(DecimalFormat.java:2089)at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)at java.text.DateFormat.parse(DateFormat.java:364)at com.java.thread.demo.threadlocal.DateUtil.parse(DateUtil.java:19)at com.java.thread.demo.threadlocal.DateUtilTest$SimpleDateFormatThread.run(DateUtilTest.java:20)
java.lang.NumberFormatException: multiple points
不安全参考:https://blog.csdn.net/lululove19870526/article/details/83684568