代码改变世界

DateFormat的线程安全问题

2011-12-19 17:55  康杜  阅读(384)  评论(0编辑  收藏  举报
在下面例子中,System.out.println(data+ " : " + tempDateStr); 打印的结果是不一样的。
public class DateFormatIsNotThreadSafe {
      static final SimpleDateFormat dateFormat =
            new SimpleDateFormat("dd-MM-yyyy");
      
      static String[] testData = {"01-10-1999", "14-10-2001", "31-10-2007"};
      
      public static void main(String[] args){
            for (final String data : testData){            
                        new Thread(){
                              public void run(){
                                    try {
                                          Date date = dateFormat.parse(data);
                                          String tempDateStr = dateFormat.format(date);
                                          System.out.println(data+ " : " + tempDateStr);
                                    } catch (ParseException e) {
                                          // TODO Auto-generated catch block
                                          e.printStackTrace();
                                    }
                              }
                        }.start();
            }
      }
}

在运行的100个线程中,有些线程运行的结果是正确的,有些线程的运行结果是错误的