国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

解決Java中SimpleDateFormat線(xiàn)程不安全的五種方案

發(fā)布時(shí)間:2021-07-05 18:40 來(lái)源:腳本之家 閱讀:0 作者:Java中文社群 欄目: 開(kāi)發(fā)技術(shù)

目錄

      1.什么是線(xiàn)程不安全?

      線(xiàn)程不安全也叫非線(xiàn)程安全,是指多線(xiàn)程執行中,程序的執行結果和預期的結果不符的情況就叫做線(xiàn)程不安全。

      線(xiàn)程不安全的代碼

      SimpleDateFormat 就是一個(gè)典型的線(xiàn)程不安全事例,接下來(lái)我們動(dòng)手來(lái)實(shí)現一下。首先我們先創(chuàng )建 10 個(gè)線(xiàn)程來(lái)格式化時(shí)間,時(shí)間格式化每次傳遞的待格式化時(shí)間都是不同的,所以程序如果正確執行將會(huì )打印 10 個(gè)不同的值,接下來(lái)我們來(lái)看具體的代碼實(shí)現:

      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      
      public class SimpleDateFormatExample {
          // 創(chuàng  )建 SimpleDateFormat 對象
          private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
      
          public static void main(String[] args) {
              // 創(chuàng  )建線(xiàn)程池
              ExecutorService threadPool = Executors.newFixedThreadPool(10);
              // 執行 10 次時(shí)間格式化
              for (int i = 0; i < 10; i++) {
                  int finalI = i;
                  // 線(xiàn)程池執行任務(wù)
                  threadPool.execute(new Runnable() {
                      @Override
                      public void run() {
                          // 創(chuàng  )建時(shí)間對象
                          Date date = new Date(finalI * 1000);
                          // 執行時(shí)間格式化并打印結果
                          System.out.println(simpleDateFormat.format(date));
                      }
                  });
              }
          }
      }

      我們預期的正確結果是這樣的(10 次打印的值都不同):


      然而,以上程序的運行結果卻是這樣的:


      從上述結果可以看出,當在多線(xiàn)程中使用 SimpleDateFormat 進(jìn)行時(shí)間格式化是線(xiàn)程不安全的。

      2.解決方案

      SimpleDateFormat 線(xiàn)程不安全的解決方案總共包含以下 5 種:

      • 將 SimpleDateFormat 定義為局部變量;
      • 使用 synchronized 加鎖執行;
      • 使用 Lock 加鎖執行(和解決方案 2 類(lèi)似);
      • 使用 ThreadLocal;
      • 使用 JDK 8 中提供的 DateTimeFormat。

      接下來(lái)我們分別來(lái)看每種解決方案的具體實(shí)現。

      ① 將SimpleDateFormat變?yōu)榫植孔兞?br />

      將 SimpleDateFormat 定義為局部變量時(shí),因為每個(gè)線(xiàn)程都是獨享 SimpleDateFormat 對象的,相當于將多線(xiàn)程程序變成“單線(xiàn)程”程序了,所以不會(huì )有線(xiàn)程不安全的問(wèn)題,具體實(shí)現代碼如下:

      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      
      public class SimpleDateFormatExample {
          public static void main(String[] args) {
              // 創(chuàng  )建線(xiàn)程池
              ExecutorService threadPool = Executors.newFixedThreadPool(10);
              // 執行 10 次時(shí)間格式化
              for (int i = 0; i < 10; i++) {
                  int finalI = i;
                  // 線(xiàn)程池執行任務(wù)
                  threadPool.execute(new Runnable() {
                      @Override
                      public void run() {
                          // 創(chuàng  )建 SimpleDateFormat 對象
                          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
                          // 創(chuàng  )建時(shí)間對象
                          Date date = new Date(finalI * 1000);
                          // 執行時(shí)間格式化并打印結果
                          System.out.println(simpleDateFormat.format(date));
                      }
                  });
              }
              // 任務(wù)執行完之后關(guān)閉線(xiàn)程池
              threadPool.shutdown();
          }
      }
      
      

      以上程序的執行結果為:


      當打印的結果都不相同時(shí),表示程序的執行是正確的,從上述結果可以看出,將 SimpleDateFormat 定義為局部變量之后,就可以成功的解決線(xiàn)程不安全問(wèn)題了。

      ② 使用synchronized加鎖

      鎖是解決線(xiàn)程不安全問(wèn)題最常用的手段,接下來(lái)我們先用 synchronized 來(lái)加鎖進(jìn)行時(shí)間格式化,實(shí)現代碼如下:

      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      
      public class SimpleDateFormatExample2 {
          // 創(chuàng  )建 SimpleDateFormat 對象
          private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
      
          public static void main(String[] args) {
              // 創(chuàng  )建線(xiàn)程池
              ExecutorService threadPool = Executors.newFixedThreadPool(10);
              // 執行 10 次時(shí)間格式化
              for (int i = 0; i < 10; i++) {
                  int finalI = i;
                  // 線(xiàn)程池執行任務(wù)
                  threadPool.execute(new Runnable() {
                      @Override
                      public void run() {
                          // 創(chuàng  )建時(shí)間對象
                          Date date = new Date(finalI * 1000);
                          // 定義格式化的結果
                          String result = null;
                          synchronized (simpleDateFormat) {
                              // 時(shí)間格式化
                              result = simpleDateFormat.format(date);
                          }
                          // 打印結果
                          System.out.println(result);
                      }
                  });
              }
              // 任務(wù)執行完之后關(guān)閉線(xiàn)程池
              threadPool.shutdown();
          }
      }
      
      

      以上程序的執行結果為:

      ③ 使用Lock加鎖

      在 Java 語(yǔ)言中,鎖的常用實(shí)現方式有兩種,除了 synchronized 之外,還可以使用手動(dòng)鎖 Lock,接下來(lái)我們使用 Lock 來(lái)對線(xiàn)程不安全的代碼進(jìn)行改造,實(shí)現代碼如下:

      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      import java.util.concurrent.locks.Lock;
      import java.util.concurrent.locks.ReentrantLock;
      
      /**
       * Lock 解決線(xiàn)程不安全問(wèn)題
       */
      public class SimpleDateFormatExample3 {
          // 創(chuàng  )建 SimpleDateFormat 對象
          private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
      
          public static void main(String[] args) {
              // 創(chuàng  )建線(xiàn)程池
              ExecutorService threadPool = Executors.newFixedThreadPool(10);
              // 創(chuàng  )建 Lock 鎖
              Lock lock = new ReentrantLock();
              // 執行 10 次時(shí)間格式化
              for (int i = 0; i < 10; i++) {
                  int finalI = i;
                  // 線(xiàn)程池執行任務(wù)
                  threadPool.execute(new Runnable() {
                      @Override
                      public void run() {
                          // 創(chuàng  )建時(shí)間對象
                          Date date = new Date(finalI * 1000);
                          // 定義格式化的結果
                          String result = null;
                          // 加鎖
                          lock.lock();
                          try {
                              // 時(shí)間格式化
                              result = simpleDateFormat.format(date);
                          } finally {
                              // 釋放鎖
                              lock.unlock();
                          }
                          // 打印結果
                          System.out.println(result);
                      }
                  });
              }
              // 任務(wù)執行完之后關(guān)閉線(xiàn)程池
              threadPool.shutdown();
          }
      }

      以上程序的執行結果為:


      從上述代碼可以看出,手動(dòng)鎖的寫(xiě)法相比于 synchronized 要繁瑣一些。

      ④ 使用ThreadLocal

      加鎖方案雖然可以正確的解決線(xiàn)程不安全的問(wèn)題,但同時(shí)也引入了新的問(wèn)題,加鎖會(huì )讓程序進(jìn)入排隊執行的流程,從而一定程度的降低了程序的執行效率,如下圖所示:


      那有沒(méi)有一種方案既能解決線(xiàn)程不安全的問(wèn)題,同時(shí)還可以避免排隊執行呢?

      答案是有的,可以考慮使用 ThreadLocal。ThreadLocal 翻譯為中文是線(xiàn)程本地變量的意思,字如其人 ThreadLocal 就是用來(lái)創(chuàng )建線(xiàn)程的私有(本地)變量的,每個(gè)線(xiàn)程擁有自己的私有對象,這樣就可以避免線(xiàn)程不安全的問(wèn)題了,實(shí)現如下:


      知道了實(shí)現方案之后,接下來(lái)我們使用具體的代碼來(lái)演示一下 ThreadLocal 的使用,實(shí)現代碼如下:

      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      
      /**
       * ThreadLocal 解決線(xiàn)程不安全問(wèn)題
       */
      public class SimpleDateFormatExample4 {
          // 創(chuàng  )建 ThreadLocal 對象,并設置默認值(new SimpleDateFormat)
          private static ThreadLocal<SimpleDateFormat> threadLocal =
                  ThreadLocal.withInitial(() -> new SimpleDateFormat("mm:ss"));
      
          public static void main(String[] args) {
              // 創(chuàng  )建線(xiàn)程池
              ExecutorService threadPool = Executors.newFixedThreadPool(10);
              // 執行 10 次時(shí)間格式化
              for (int i = 0; i < 10; i++) {
                  int finalI = i;
                  // 線(xiàn)程池執行任務(wù)
                  threadPool.execute(new Runnable() {
                      @Override
                      public void run() {
                          // 創(chuàng  )建時(shí)間對象
                          Date date = new Date(finalI * 1000);
                          // 格式化時(shí)間
                          String result = threadLocal.get().format(date);
                          // 打印結果
                          System.out.println(result);
                      }
                  });
              }
              // 任務(wù)執行完之后關(guān)閉線(xiàn)程池
              threadPool.shutdown();
          }
      }
      
      

      以上程序的執行結果為:

      ThreadLocal和局部變量的區別

      首先來(lái)說(shuō) ThreadLocal 不等于局部變量,這里的“局部變量”指的是像 2.1 示例代碼中的局部變量, ThreadLocal 和局部變量最大的區別在于:ThreadLocal 屬于線(xiàn)程的私有變量,如果使用的是線(xiàn)程池,那么 ThreadLocal 中的變量是可以重復使用的,而代碼級別的局部變量,每次執行時(shí)都會(huì )創(chuàng )建新的局部變量,二者區別如下圖所示:

      更多關(guān)于 ThreadLocal 的內容,可以訪(fǎng)問(wèn)磊哥前面的文章《》。

      ⑤ 使用DateTimeFormatter

      以上 4 種解決方案都是因為 SimpleDateFormat 是線(xiàn)程不安全的,所以我們需要加鎖或者使用 ThreadLocal 來(lái)處理,然而,JDK 8 之后我們就有了新的選擇,如果使用的是 JDK 8+ 版本,就可以直接使用 JDK 8 中新增的、安全的時(shí)間格式化工具類(lèi) DateTimeFormatter 來(lái)格式化時(shí)間了,接下來(lái)我們來(lái)具體實(shí)現一下。

      使用 DateTimeFormatter 必須要配合 JDK 8 中新增的時(shí)間對象 LocalDateTime 來(lái)使用,因此在操作之前,我們可以先將 Date 對象轉換成 LocalDateTime,然后再通過(guò) DateTimeFormatter 來(lái)格式化時(shí)間,具體實(shí)現代碼如下:

      import java.time.LocalDateTime;
      import java.time.ZoneId;
      import java.time.format.DateTimeFormatter;
      import java.util.Date;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      
      /**
       * DateTimeFormatter 解決線(xiàn)程不安全問(wèn)題
       */
      public class SimpleDateFormatExample5 {
          // 創(chuàng  )建 DateTimeFormatter 對象
          private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("mm:ss");
      
          public static void main(String[] args) {
              // 創(chuàng  )建線(xiàn)程池
              ExecutorService threadPool = Executors.newFixedThreadPool(10);
              // 執行 10 次時(shí)間格式化
              for (int i = 0; i < 10; i++) {
                  int finalI = i;
                  // 線(xiàn)程池執行任務(wù)
                  threadPool.execute(new Runnable() {
                      @Override
                      public void run() {
                          // 創(chuàng  )建時(shí)間對象
                          Date date = new Date(finalI * 1000);
                          // 將 Date 轉換成 JDK 8 中的時(shí)間類(lèi)型 LocalDateTime
                          LocalDateTime localDateTime =
                                  LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
                          // 時(shí)間格式化
                          String result = dateTimeFormatter.format(localDateTime);
                          // 打印結果
                          System.out.println(result);
                      }
                  });
              }
              // 任務(wù)執行完之后關(guān)閉線(xiàn)程池
              threadPool.shutdown();
          }
      }
      
      

      以上程序的執行結果為:

      3.線(xiàn)程不安全原因分析

      要了解 SimpleDateFormat 為什么是線(xiàn)程不安全的?我們需要查看并分析 SimpleDateFormat 的源碼才行,那我們先從使用的方法 format 入手,源碼如下:

      private StringBuffer format(Date date, StringBuffer toAppendTo,
                                      FieldDelegate delegate) {
          // 注意此行代碼
          calendar.setTime(date);
      
          boolean useDateFormatSymbols = useDateFormatSymbols();
      
          for (int i = 0; i < compiledPattern.length; ) {
              int tag = compiledPattern[i] >>> 8;
              int count = compiledPattern[i++] & 0xff;
              if (count == 255) {
                  count = compiledPattern[i++] << 16;
                  count |= compiledPattern[i++];
              }
      
              switch (tag) {
                  case TAG_QUOTE_ASCII_CHAR:
                      toAppendTo.append((char)count);
                      break;
      
                  case TAG_QUOTE_CHARS:
                      toAppendTo.append(compiledPattern, i, count);
                      i += count;
                      break;
      
                  default:
                      subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
                      break;
              }
          }
          return toAppendTo;
      }

      也許是好運使然,沒(méi)想到剛開(kāi)始分析第一個(gè)方法就找到了線(xiàn)程不安全的問(wèn)題所在。

      從上述源碼可以看出,在執行 SimpleDateFormat.format 方法時(shí),會(huì )使用 calendar.setTime 方法將輸入的時(shí)間進(jìn)行轉換,那么我們想象一下這樣的場(chǎng)景:

      • 線(xiàn)程 1 執行了 calendar.setTime(date) 方法,將用戶(hù)輸入的時(shí)間轉換成了后面格式化時(shí)所需要的時(shí)間;
      • 線(xiàn)程 1 暫停執行,線(xiàn)程 2 得到 CPU 時(shí)間片開(kāi)始執行;
      • 線(xiàn)程 2 執行了 calendar.setTime(date) 方法,對時(shí)間進(jìn)行了修改;
      • 線(xiàn)程 2 暫停執行,線(xiàn)程 1 得出 CPU 時(shí)間片繼續執行,因為線(xiàn)程 1 和線(xiàn)程 2 使用的是同一對象,而時(shí)間已經(jīng)被線(xiàn)程 2 修改了,所以此時(shí)當線(xiàn)程 1 繼續執行的時(shí)候就會(huì )出現線(xiàn)程安全的問(wèn)題了。

      正常的情況下,程序的執行是這樣的:

      非線(xiàn)程安全的執行流程是這樣的:


      在多線(xiàn)程執行的情況下,線(xiàn)程 1 的 date1 和線(xiàn)程 2 的 date2,因為執行順序的問(wèn)題,最終都被格式化成 date2 formatted,而非線(xiàn)程 1 date1 formatted 和線(xiàn)程 2 date2 formatted,這樣就會(huì )導致線(xiàn)程不安全的問(wèn)題。

      4.各方案優(yōu)缺點(diǎn)總結

      如果使用的是 JDK 8+ 版本,可以直接使用線(xiàn)程安全的 DateTimeFormatter 來(lái)進(jìn)行時(shí)間格式化,如果使用的 JDK 8 以下版本或者改造老的 SimpleDateFormat 代碼,可以考慮使用 synchronized 或 ThreadLocal 來(lái)解決線(xiàn)程不安全的問(wèn)題。因為實(shí)現方案 1 局部變量的解決方案,每次執行的時(shí)候都會(huì )創(chuàng )建新的對象,因此不推薦使用。synchronized 的實(shí)現比較簡(jiǎn)單,而使用 ThreadLocal 可以避免加鎖排隊執行的問(wèn)題。

      到此這篇關(guān)于解決Java中SimpleDateFormat線(xiàn)程不安全的五種方案的文章就介紹到這了,更多相關(guān)SimpleDateFormat線(xiàn)程不安全內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

      免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。

      人妻少妇精品视频专区| 少妇爆乳无码专区AV无码| 久久无码人妻精品一区二区三区| 色欲AV无码无在线观看| 日日摸日日踫夜夜爽无码| 黄网站色视频免费观看无下载|