原文:https://blog.csdn.net/baofeidyz/article/details/81307478
如何讓SimpleDateFormat保持安全運行?
方案一 每次都去new
這種方案最簡單,但是會導致開銷比較大,不推薦
方案二 使用ThreadLocal保障每個線程都有一個SimpleDateFormat
這個方法是我在這里看到的:https://www.jianshu.com/p/d9977a048dab
我摘一下主要內容:
---------------------
作者:暴沸
來源:CSDN
原文:https://blog.csdn.net/baofeidyz/article/details/81307478
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
public class TestSimpleDateFormat2 { // (1)創建threadlocal實例 static ThreadLocal<DateFormat> safeSdf = new ThreadLocal<DateFormat>(){ @Override protected SimpleDateFormat initialValue(){ return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; public static void main(String[] args) { // (2)創建多個線程,並啟動 for (int i = 0; i < 10; ++i) { Thread thread = new Thread(new Runnable() { public void run() { try {// (3)使用單例日期實例解析文本 System.out.println(safeSdf.get().parse("2017-12-13 15:17:27")); } catch (ParseException e) { e.printStackTrace(); } } }); thread.start();// (4)啟動線程 } } }
方案三 使用第三方包
這個我有嘗試cn.hutool和common-lang3提供的FastDateFormat
最后的結果其實並不滿意,因為這兩個包都沒能幫助我檢查非正常時間,比如2018-07-32這種日期也被認為是正確的時期格式了
方案四 使用JDK8提供的DateTimeFormatter
這個方案就比較完美了,該有的都有了。
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");