SimpleDateFormat是線程不安全的

示例

@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));
                    // 根據(jù)請求中的時間往后推算月數(shù)
                    calendar.add(Calendar.MONTH, 6);
                    log.info(time + "--->" + FORMATTER.format(calendar.getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}

結(jié)果

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

可以看到,結(jié)果不對,也死鎖了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容