SimpleDateFormat 非线程安全,使用 ThreadLocal 可以保证在多线程程序中时间格式化的正确性。
package com.learn.corejava.threading;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LocalThreadMain {
public static void main(String[] args) {
ThreadLocal<SimpleDateFormat> localFormatter = ThreadLocal.withInitial(()-> new SimpleDateFormat("yyyy-MM-dd"));
String dateString = localFormatter.get().format(new Date());
System.out.println(dateString);
}
}