java.text.SimpleDateFormat 不是线程安全的。
java.text.SimpleDateFormat 不是线程安全的。
Synchronization Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally
以上行内容出现在 SimpleDateFormat 类的 JavaDoc 中。
这是否意味着我们不应该将 SimpleDateFormat 对象创建为静态的。
如果我们将其创建为静态的,则无论我们在何处使用此对象,都需要将其放置在同步块中。
admin 更改状态以发布 2023年5月23日
是的,SimpleDateFormat 不是线程安全的,建议在解析日期时以同步方式访问。
public Date convertStringToDate(String dateString) throws ParseException { Date result; synchronized(df) { result = df.parse(dateString); } return result; }
另一种方法是使用 http://code.google.com/p/safe-simple-date-format/downloads/list