joda datetimeformat如何影响simpledateformat

时间:2016-02-25 06:52:15

标签: java multithreading jodatime

众所周知,simpleDateFormat不是线程安全的。面对多线程时,simpleDateFormat可能会抛出一些异常。所以,我决定改用joda-time。

然而,当我将joda-time与simpleDateFormat一起使用时,发生了一些奇怪的事情。

期待结果:

simpleDateFormat抛出异常,joda-time成功解析。

实际结果:

都成功解析了。

请看下面我为测试编写的代码。

public class MultiThreadDateTest {

  private static SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd");
  private static DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
  private static final int THREAD_SIZE = 4;

  public static void main(String[] args) throws InterruptedException {
    for (int i = 0; i < THREAD_SIZE; i++) {
      new Thread(new JavaDateThread()).start();
      new Thread(new JodaDateThread()).start();
    }
  }

  private static class JavaDateThread implements Runnable {

    @Override
    public void run() {
      try {
        Date date = dformat.parse("1999-01-01");
        System.out.println(Thread.currentThread().getId() + ": " + date);
      } catch (ParseException e) {
        e.printStackTrace();
      }
    }
  }

  private static class JodaDateThread implements Runnable {

    @Override
    public void run() {
      Date date = format.parseDateTime("2000-01-01").toDate();
      System.out.println(Thread.currentThread().getId() + ": " + date);
    }
  }
}

0 个答案:

没有答案