SimpleDateFormat是线程不安全的

2021-02-25 17:17:19 浏览数 (1)

示例

代码语言:javascript复制
@Slf4j
class Test {
    
    private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd");

    public static void main(String[] args) {
        
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i  ) {
            executorService.submit(() -> {
                Calendar calendar = Calendar.getInstance();
                String time = "2021-"   (int) (Math.random() * 10)   "-"   (int) (Math.random() * 10);
                try {
                    calendar.setTime(FORMATTER.parse(time));
                    // 根据请求中的时间往后推算月数
                    calendar.add(Calendar.MONTH, 6);
                    log.info(time   "--->"   FORMATTER.format(calendar.getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}

结果

代码语言:javascript复制
14:42:17.971 [pool-1-thread-9] INFO Test - 2021-3-1--->117622972-02-29
14:42:17.971 [pool-1-thread-5] INFO Test - 2021-7-7--->117622972-02-29
14:42:17.971 [pool-1-thread-8] INFO Test - 2021-4-7--->117622972-02-29
14:42:17.971 [pool-1-thread-1] INFO Test - 2021-9-9--->0007-09-01

可以看到,结果不对,也死锁了。

0 人点赞