SimpleDateFormat和DateFormat类不是线程安全的。
生活随笔
收集整理的这篇文章主要介绍了
SimpleDateFormat和DateFormat类不是线程安全的。
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
为什么80%的码农都做不了架构师?>>>
比较好的两种方法
import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class ConcurrentDateUtil { private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {@Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}}; public static Date parse(String dateStr) throws ParseException { return threadLocal.get().parse(dateStr);} public static String format(Date date) { return threadLocal.get().format(date);} } import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class ThreadLocalDateUtil { private static final String date_format = "yyyy-MM-dd HH:mm:ss"; private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(); public static DateFormat getDateFormat() { DateFormat df = threadLocal.get(); if(df==null){ df = new SimpleDateFormat(date_format); threadLocal.set(df); } return df; } public static String formatDate(Date date) throws ParseException { return getDateFormat().format(date);} public static Date parse(String strDate) throws ParseException { return getDateFormat().parse(strDate);} }转载于:https://my.oschina.net/reone/blog/534050
总结
以上是生活随笔为你收集整理的SimpleDateFormat和DateFormat类不是线程安全的。的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: freemarker入门实例与源码研究准
- 下一篇: jquery之ajax请求工具类