SimpleDateFormat線程不安全原因


  • parse 方法為什么不線程安全

1.有一個共享變量calendar,而這個共享變量的訪問沒有做到線程安全

2.parse方法生成CalendarBuilder,然后通過CalendarBuilder 設值到calendar,最后calendar.getTime();

clipboard

3.api方法說明 This parsing operation uses the calendar to produce a Date. All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information.

  • format方法為什么不線程安全

1.有一個共享變量calendar,而這個共享變量的訪問沒有做到線程安全

2.當使用format方法時,實際是給calent共享變量設置date值,然后調用subFormat將date轉化成字符串

clipboard[1]

--------------------

clipboard[2]

-------------------

clipboard[3]

  • 解決方案

1.創建一個共享的SimpleDateFormat實例變量,但是在使用的時候,需要對這個變量進行同步

2.使用ThreadLocal為每個線程都創建一個線程獨享SimpleDateFormat變量

3.需要的時候創建局部變量


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM