SimpleDateFormat

@Test
public void testParse() {
    ExecutorService executorService = Executors.newCachedThreadPool();
    List<String> dateStrList = Lists.newArrayList(
            "2018-04-01 10:00:01",
            "2018-04-02 11:00:02",
            "2018-04-03 12:00:03",
            "2018-04-04 13:00:04",
            "2018-04-05 14:00:05"
    );
    /**
     * 注意这个地方很容易犯错!!!
     * 因此这里 SimpleDateFormat 对象是不能公用的!!!
     */
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    for (String str : dateStrList) {
        executorService.execute(() -> {
            try {
                simpleDateFormat.parse(str);
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

并发环境下使用SimpleDateFormat的parse方法有线程安全问题!java

  • 线程安全问题的缘由:
    • 在SimpleDateFormat转换日期是经过Calendar对象来操做的
      • 若是此时线程A将calendar清空且没有设置新值,
      • 线程B也进入parse方法用到了SimpleDateFormat对象中的calendar对象,
      • 此时就会产生线程安全问题!
相关文章
相关标签/搜索