java,SimpleDateFormat(jdk1.7)線程不安全和DateTimeFormatter(jdk1.8)線程安全區別與使用

區別:
SimpleDateFormat是線程不安全的,在併發環境下使用SimpleDateFormat(方法見使用);
DateTimeFormatter是線程安全的,jdk8自帶( java.time.format.DateTimeFormatter);
Joda time裏的DateTimeFormat也是線程安全。

多線程中使用:
SimpleDateFormat:

  1. 在需要執行時間格式化的地方都新建SimpleDateFormat實例,使用局部變量來存放SimpleDateFormat實例。
    缺點:可能會導致短期內創建大量的SimpleDateFormat實例,如解析一個excel表格裏的字符串日期。
   public static String formateDate(Date date){
       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       return format.format(date);
   }
  1. 爲了避免創建大量的SimpleDateFormat實例,往往會考慮把SimpleDateFormat實例設爲靜態成員變量,共享SimpleDateFormat對象。這種情況下需要對SimpleDateFormat添加同步。、
    缺點:在高併發的環境下會導致解析被阻塞
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  public static String formatDate(Date date){
      synchronized(sdf){
          return sdf.format(date);
      }
  }
  1. 使用ThreadLocal來限制SimpleDateFormat只能在線程內共享,這樣就避免了多線程導致的線程安全問題。
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
     @Override
     protected DateFormat initialValue() {
         return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     }
 };

 public static String format(Date date) {
     return threadLocal.get().format(date);
 }

DateTimeFormatter
線程安全,可直接使用

     LocalDateTime now = LocalDateTime.now();
     DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMdd hh:mm:ss");
     String nowTime = now .format(format);
     String nowStr = now.toString();
     int nowYear = now.getYear();
     Month nowMonth = now.getMonth();

代碼中打印結果:
在這裏插入圖片描述

發佈了48 篇原創文章 · 獲贊 13 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章