SimpleDateFormat是线程不安全的

2021-02-22  本文已影响0人  悠扬前奏

示例

@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();
                }
            });
        }
    }
}

结果

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

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

上一篇下一篇

猜你喜欢

热点阅读