• parse 方法为什么不线程安全

1.有一个共享变量calendar,而这个共享变量的访问没有做到线程安全

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

SimpleDateFormat线程不安全原因

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转化成字符串

SimpleDateFormat线程不安全原因

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

SimpleDateFormat线程不安全原因

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

SimpleDateFormat线程不安全原因

  • 解决方案

1.创建一个共享的SimpleDateFormat实例变量,但是在使用的时候,需要对这个变量进行同步

2.使用ThreadLocal为每个线程都创建一个线程独享SimpleDateFormat变量

3.需要的时候创建局部变量

相关文章:

  • 2021-11-20
  • 2021-10-10
  • 2021-07-27
  • 2023-03-24
  • 2021-10-31
  • 2021-10-08
  • 2021-08-13
猜你喜欢
  • 2021-11-14
  • 2022-02-24
  • 2021-11-04
  • 2021-09-05
相关资源
相似解决方案