java.text.SimpleDateFormat是非线程安全的,所以,如果一个SimpleDateFormat对象作为类成员或者类的静态成员在多线程环境下被调用时,会出现“时间错乱”的现象。
替代方案:
1.每次使用SimpleDateFormat前都new一个新对象,这个做法的缺点是效率较低;
2.使用apache的commons-lang包下的FastDateFormat,代码如下:
FastDateFormat fdfWithoutTime=FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss",TimeZone.getDefault(), Locale.getDefault());
String time=fdfWithoutTime.format(new Date());
(很不幸的是FastDateFormat只能进行format不能进行parse,据说有个叫JodaTime的库比较好用,木有用过)
本文讨论了java.text.SimpleDateFormat在多线程环境下的线程安全问题,并提出了两种解决方案:每次使用前创建新对象或使用FastDateFormat。然而,FastDateFormat仅支持格式化而不支持解析。
1057

被折叠的 条评论
为什么被折叠?



