@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