Java中的ThreadLocal除了编写不可变的类外,还是一种实现线程安全的方法。由于SimpleDateFormat不是线程安全的,因此可以使用ThreadLocal使其成为线程安全的。
class DateFormatter{ private static ThreadLocal<SimpleDateFormat> outDateFormatHolder = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("MM/dd/yyyy"); }};private static ThreadLocal<SimpleDateFormat> inDateFormatHolder = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd"); }};public static String formatDate(String date) throws ParseException { return outDateFormatHolder.get().format( inDateFormatHolder.get().parse(date));} }


