成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

SimpleDateFormat線程不安全的5種解決方案!

開(kāi)發(fā) 前端
線程不安全也叫非線程安全,是指多線程執(zhí)行中,程序的執(zhí)行結(jié)果和預(yù)期的結(jié)果不符的情況就叫著線程不安全。

[[399716]]

本文轉(zhuǎn)載自微信公眾號(hào)「Java中文社群」,作者磊哥。轉(zhuǎn)載本文請(qǐng)聯(lián)系Java中文社群公眾號(hào)。

1.什么是線程不安全?

線程不安全也叫非線程安全,是指多線程執(zhí)行中,程序的執(zhí)行結(jié)果和預(yù)期的結(jié)果不符的情況就叫著線程不安全。

線程不安全的代碼

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

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3. import java.util.concurrent.ExecutorService; 
  4. import java.util.concurrent.Executors; 
  5.  
  6. public class SimpleDateFormatExample { 
  7.     // 創(chuàng)建 SimpleDateFormat 對(duì)象 
  8.     private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); 
  9.  
  10.     public static void main(String[] args) { 
  11.         // 創(chuàng)建線程池 
  12.         ExecutorService threadPool = Executors.newFixedThreadPool(10); 
  13.         // 執(zhí)行 10 次時(shí)間格式化 
  14.         for (int i = 0; i < 10; i++) { 
  15.             int finalI = i; 
  16.             // 線程池執(zhí)行任務(wù) 
  17.             threadPool.execute(new Runnable() { 
  18.                 @Override 
  19.                 public void run() { 
  20.                     // 創(chuàng)建時(shí)間對(duì)象 
  21.                     Date date = new Date(finalI * 1000); 
  22.                     // 執(zhí)行時(shí)間格式化并打印結(jié)果 
  23.                     System.out.println(simpleDateFormat.format(date)); 
  24.                 } 
  25.             }); 
  26.         } 
  27.     } 

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

然而,以上程序的運(yùn)行結(jié)果卻是這樣的:

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

2.解決方案

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

  1. 將 SimpleDateFormat 定義為局部變量;
  2. 使用 synchronized 加鎖執(zhí)行;
  3. 使用 Lock 加鎖執(zhí)行(和解決方案 2 類似);
  4. 使用 ThreadLocal;
  5. 使用 JDK 8 中提供的 DateTimeFormat。

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

① SimpleDateFormat改為局部變量

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

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3. import java.util.concurrent.ExecutorService; 
  4. import java.util.concurrent.Executors; 
  5.  
  6. public class SimpleDateFormatExample { 
  7.     public static void main(String[] args) { 
  8.         // 創(chuàng)建線程池 
  9.         ExecutorService threadPool = Executors.newFixedThreadPool(10); 
  10.         // 執(zhí)行 10 次時(shí)間格式化 
  11.         for (int i = 0; i < 10; i++) { 
  12.             int finalI = i; 
  13.             // 線程池執(zhí)行任務(wù) 
  14.             threadPool.execute(new Runnable() { 
  15.                 @Override 
  16.                 public void run() { 
  17.                     // 創(chuàng)建 SimpleDateFormat 對(duì)象 
  18.                     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); 
  19.                     // 創(chuàng)建時(shí)間對(duì)象 
  20.                     Date date = new Date(finalI * 1000); 
  21.                     // 執(zhí)行時(shí)間格式化并打印結(jié)果 
  22.                     System.out.println(simpleDateFormat.format(date)); 
  23.                 } 
  24.             }); 
  25.         } 
  26.         // 任務(wù)執(zhí)行完之后關(guān)閉線程池 
  27.         threadPool.shutdown(); 
  28.     } 

以上程序的執(zhí)行結(jié)果為:

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

② 使用synchronized加鎖

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

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3. import java.util.concurrent.ExecutorService; 
  4. import java.util.concurrent.Executors; 
  5.  
  6. public class SimpleDateFormatExample2 { 
  7.     // 創(chuàng)建 SimpleDateFormat 對(duì)象 
  8.     private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); 
  9.  
  10.     public static void main(String[] args) { 
  11.         // 創(chuàng)建線程池 
  12.         ExecutorService threadPool = Executors.newFixedThreadPool(10); 
  13.         // 執(zhí)行 10 次時(shí)間格式化 
  14.         for (int i = 0; i < 10; i++) { 
  15.             int finalI = i; 
  16.             // 線程池執(zhí)行任務(wù) 
  17.             threadPool.execute(new Runnable() { 
  18.                 @Override 
  19.                 public void run() { 
  20.                     // 創(chuàng)建時(shí)間對(duì)象 
  21.                     Date date = new Date(finalI * 1000); 
  22.                     // 定義格式化的結(jié)果 
  23.                     String result = null
  24.                     synchronized (simpleDateFormat) { 
  25.                         // 時(shí)間格式化 
  26.                         result = simpleDateFormat.format(date); 
  27.                     } 
  28.                     // 打印結(jié)果 
  29.                     System.out.println(result); 
  30.                 } 
  31.             }); 
  32.         } 
  33.         // 任務(wù)執(zhí)行完之后關(guān)閉線程池 
  34.         threadPool.shutdown(); 
  35.     } 

以上程序的執(zhí)行結(jié)果為:

③ 使用Lock加鎖

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

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3. import java.util.concurrent.ExecutorService; 
  4. import java.util.concurrent.Executors; 
  5. import java.util.concurrent.locks.Lock; 
  6. import java.util.concurrent.locks.ReentrantLock; 
  7.  
  8. /** 
  9.  * Lock 解決線程不安全問(wèn)題 
  10.  */ 
  11. public class SimpleDateFormatExample3 { 
  12.     // 創(chuàng)建 SimpleDateFormat 對(duì)象 
  13.     private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); 
  14.  
  15.     public static void main(String[] args) { 
  16.         // 創(chuàng)建線程池 
  17.         ExecutorService threadPool = Executors.newFixedThreadPool(10); 
  18.         // 創(chuàng)建 Lock 鎖 
  19.         Lock lock = new ReentrantLock(); 
  20.         // 執(zhí)行 10 次時(shí)間格式化 
  21.         for (int i = 0; i < 10; i++) { 
  22.             int finalI = i; 
  23.             // 線程池執(zhí)行任務(wù) 
  24.             threadPool.execute(new Runnable() { 
  25.                 @Override 
  26.                 public void run() { 
  27.                     // 創(chuàng)建時(shí)間對(duì)象 
  28.                     Date date = new Date(finalI * 1000); 
  29.                     // 定義格式化的結(jié)果 
  30.                     String result = null
  31.                     // 加鎖 
  32.                     lock.lock(); 
  33.                     try { 
  34.                         // 時(shí)間格式化 
  35.                         result = simpleDateFormat.format(date); 
  36.                     } finally { 
  37.                         // 釋放鎖 
  38.                         lock.unlock(); 
  39.                     } 
  40.                     // 打印結(jié)果 
  41.                     System.out.println(result); 
  42.                 } 
  43.             }); 
  44.         } 
  45.         // 任務(wù)執(zhí)行完之后關(guān)閉線程池 
  46.         threadPool.shutdown(); 
  47.     } 

以上程序的執(zhí)行結(jié)果為:

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

④ 使用ThreadLocal

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

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

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

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

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3. import java.util.concurrent.ExecutorService; 
  4. import java.util.concurrent.Executors; 
  5.  
  6. /** 
  7.  * ThreadLocal 解決線程不安全問(wèn)題 
  8.  */ 
  9. public class SimpleDateFormatExample4 { 
  10.     // 創(chuàng)建 ThreadLocal 對(duì)象,并設(shè)置默認(rèn)值(new SimpleDateFormat) 
  11.     private static ThreadLocal<SimpleDateFormat> threadLocal = 
  12.             ThreadLocal.withInitial(() -> new SimpleDateFormat("mm:ss")); 
  13.  
  14.     public static void main(String[] args) { 
  15.         // 創(chuàng)建線程池 
  16.         ExecutorService threadPool = Executors.newFixedThreadPool(10); 
  17.         // 執(zhí)行 10 次時(shí)間格式化 
  18.         for (int i = 0; i < 10; i++) { 
  19.             int finalI = i; 
  20.             // 線程池執(zhí)行任務(wù) 
  21.             threadPool.execute(new Runnable() { 
  22.                 @Override 
  23.                 public void run() { 
  24.                     // 創(chuàng)建時(shí)間對(duì)象 
  25.                     Date date = new Date(finalI * 1000); 
  26.                     // 格式化時(shí)間 
  27.                     String result = threadLocal.get().format(date); 
  28.                     // 打印結(jié)果 
  29.                     System.out.println(result); 
  30.                 } 
  31.             }); 
  32.         } 
  33.         // 任務(wù)執(zhí)行完之后關(guān)閉線程池 
  34.         threadPool.shutdown(); 
  35.     } 

以上程序的執(zhí)行結(jié)果為:

ThreadLocal和局部變量的區(qū)別

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

更多關(guān)于 ThreadLocal 的內(nèi)容,可以訪問(wèn)磊哥前面的文章《ThreadLocal不好用?那是你沒(méi)用對(duì)!》。

⑤ 使用DateTimeFormatter

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

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

  1. import java.time.LocalDateTime; 
  2. import java.time.ZoneId; 
  3. import java.time.format.DateTimeFormatter; 
  4. import java.util.Date
  5. import java.util.concurrent.ExecutorService; 
  6. import java.util.concurrent.Executors; 
  7.  
  8. /** 
  9.  * DateTimeFormatter 解決線程不安全問(wèn)題 
  10.  */ 
  11. public class SimpleDateFormatExample5 { 
  12.     // 創(chuàng)建 DateTimeFormatter 對(duì)象 
  13.     private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("mm:ss"); 
  14.  
  15.     public static void main(String[] args) { 
  16.         // 創(chuàng)建線程池 
  17.         ExecutorService threadPool = Executors.newFixedThreadPool(10); 
  18.         // 執(zhí)行 10 次時(shí)間格式化 
  19.         for (int i = 0; i < 10; i++) { 
  20.             int finalI = i; 
  21.             // 線程池執(zhí)行任務(wù) 
  22.             threadPool.execute(new Runnable() { 
  23.                 @Override 
  24.                 public void run() { 
  25.                     // 創(chuàng)建時(shí)間對(duì)象 
  26.                     Date date = new Date(finalI * 1000); 
  27.                     // 將 Date 轉(zhuǎn)換成 JDK 8 中的時(shí)間類型 LocalDateTime 
  28.                     LocalDateTime localDateTime = 
  29.                             LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); 
  30.                     // 時(shí)間格式化 
  31.                     String result = dateTimeFormatter.format(localDateTime); 
  32.                     // 打印結(jié)果 
  33.                     System.out.println(result); 
  34.                 } 
  35.             }); 
  36.         } 
  37.         // 任務(wù)執(zhí)行完之后關(guān)閉線程池 
  38.         threadPool.shutdown(); 
  39.     } 

以上程序的執(zhí)行結(jié)果為:

3.線程不安全原因分析

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

  1. private StringBuffer format(Date date, StringBuffer toAppendTo, 
  2.                                 FieldDelegate delegate) { 
  3.     // 注意此行代碼 
  4.     calendar.setTime(date); 
  5.  
  6.     boolean useDateFormatSymbols = useDateFormatSymbols(); 
  7.  
  8.     for (int i = 0; i < compiledPattern.length; ) { 
  9.         int tag = compiledPattern[i] >>> 8; 
  10.         int count = compiledPattern[i++] & 0xff; 
  11.         if (count == 255) { 
  12.             count = compiledPattern[i++] << 16; 
  13.             count |= compiledPattern[i++]; 
  14.         } 
  15.  
  16.         switch (tag) { 
  17.             case TAG_QUOTE_ASCII_CHAR: 
  18.                 toAppendTo.append((char)count); 
  19.                 break; 
  20.  
  21.             case TAG_QUOTE_CHARS: 
  22.                 toAppendTo.append(compiledPattern, i, count); 
  23.                 i += count
  24.                 break; 
  25.  
  26.             default
  27.                 subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols); 
  28.                 break; 
  29.         } 
  30.     } 
  31.     return toAppendTo; 

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

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

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

正常的情況下,程序的執(zhí)行是這樣的:

非線程安全的執(zhí)行流程是這樣的:

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

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

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

 

責(zé)任編輯:武曉燕 來(lái)源: Java中文社群
相關(guān)推薦

2012-04-16 10:12:54

Java線程

2020-04-22 20:35:02

HashMap線程安全

2024-01-19 08:42:45

Java線程字符串

2015-07-01 14:48:51

2024-03-22 12:29:03

HashMap線程

2019-06-14 05:00:05

2020-02-21 14:15:40

SimpleDateFJava多線程

2021-12-17 11:06:39

linux設(shè)計(jì)高可用

2023-06-01 19:24:16

2010-01-12 12:15:25

SOA安全解決方案

2023-09-18 08:01:06

Spring管理Mybatis

2015-03-16 11:40:23

2020-11-03 12:32:25

影子物聯(lián)網(wǎng)物聯(lián)網(wǎng)IOT

2021-04-04 23:16:52

安全刷臉銀行

2009-08-03 16:58:59

C#不安全代碼

2020-03-11 09:57:10

數(shù)據(jù)安全網(wǎng)絡(luò)安全網(wǎng)絡(luò)攻擊

2009-07-15 17:09:32

Swing線程

2010-12-21 17:39:59

2010-12-24 13:05:22

2014-04-09 09:37:29

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 午夜免费在线 | 欧美精品一区在线发布 | 日本精品在线观看 | 男人的天堂在线视频 | 亚洲免费av一区 | 国产一级在线 | 精品国产一区久久 | 五月综合激情婷婷 | 激情五月婷婷综合 | 国产成人午夜高潮毛片 | 波多野结衣精品在线 | 久久久性色精品国产免费观看 | 九九亚洲 | 久久久综合网 | 日日操夜夜操天天操 | 成人h动漫亚洲一区二区 | 国产成人99久久亚洲综合精品 | 欧美日本韩国一区二区三区 | 国产成人综合在线 | 一级毛片视频 | 日韩一级免费看 | 黄色大片免费播放 | 中文字幕免费在线 | 精品日韩一区 | 精品一二区| 国产福利资源在线 | 亚洲91精品 | 国产1区2区3区 | 人人做人人澡人人爽欧美 | 国产精品视频在线播放 | 国精久久| 欧美精品乱码99久久影院 | 欧美激情视频一区二区三区在线播放 | 日日夜夜影院 | 亚洲一区二区久久 | 亚洲一二三区在线观看 | 欧美一区永久视频免费观看 | 天堂在线中文 | 日韩成人中文字幕 | 四季久久免费一区二区三区四区 | 日本不卡一区二区三区在线观看 |