导致SimpleDateFormat出现多线程安全问题的原因,是因为:SimpleDateFormat处理复杂,Jdk的实现中使用了成员变量来传递参数,这就造成在多线程的时候会出现错误
一些常见的错误代码大致如下
public class DateFormatTest {
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
xxxxxx...
}
错误浮现dmo
最笨的解决办法:不使用static SimpleDateFormat,每次使用都直接new一个package dateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatTest { private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); public static void main(String[] args) { Date today = new Date(); Date tomorrow = new Date(today.getTime() + 1000 * 60 * 60 * 24); System.out.println(today); System.out.println(tomorrow); Thread thread1 = new Thread(new Thread1(dateFormat, today)); thread1.start(); Thread thread2 = new Thread(new Thread2(dateFormat, tomorrow)); thread2.start(); } } class Thread1 implements Runnable { private SimpleDateFormat dateFormat; private Date date; public Thread1(SimpleDateFormat dateFormat, Date date) { this.dateFormat = dateFormat; this.date = date; } public void run() { for (;;) { System.out.println("Thread1.run" + date); String strDate = dateFormat.format(date); if (!"2015-11-03".equals(strDate)) { System.err.println("today=" + strDate); System.exit(0); } } } } class Thread2 implements Runnable { private SimpleDateFormat dateFormat; private Date date; public Thread2(SimpleDateFormat dateFormat, Date date) { this.dateFormat = dateFormat; this.date = date; } public void run() { for (;;) { System.out.println("Thread2.run" + date); String strDate = dateFormat.format(date); if (!"2015-11-04".equals(strDate)) { System.err.println("tomorrow=" + strDate); System.exit(0); } } } }
比较高大上的解决办法joda