若是一個類的對象同時被多個線程訪問,若是不作特殊的同步或併發處理,很容易表現出線程不安全的現象,好比拋出異常、邏輯處理錯誤等,這種類咱們就稱爲線程不安全的類。java
在此處主要講解下SimpleDateFormat類以及JodaTime安全
SimpleDateFormat是線程不安全的類 例如:併發
public class DateFormatExample1 { private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); public static int clientTotal = 1000;//請求總數 private static void update() throws ParseException { simpleDateFormat.parse("20181008"); } public static void main(String[] args)throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); //定義線程池 for (int i = 0; i < clientTotal; i++) executorService.execute(() -> { try { update(); } catch (ParseException e) { e.printStackTrace(); } }); } }
而解決這個問題的方法是能夠採用堆棧封閉的方式maven
public class DateFormatExample2 { public static int clientTotal = 1000;//請求總數 private static void update() throws ParseException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); simpleDateFormat.parse("20180208"); } public static void main(String[] args)throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); //定義線程池 for (int i = 0; i < clientTotal; i++) executorService.execute(() -> { try { update(); } catch (ParseException e) { e.printStackTrace(); } }); } }
而jodatime提供了一個DateTimeFormatter類,這個類是線程安全的,而且在實際應用中還有更多的優點。因此在實際的開發中推薦使用jodatime線程
使用時首先須要添加maven依賴包code
<dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.9</version> </dependency>
public class DateFormatExample2 { public static int clientTotal = 1000;//請求總數 private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd"); private static void update() throws ParseException { dateTimeFormatter.parseDateTime("20181008"); } public static void main(String[] args)throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); //定義線程池 for (int i = 0; i < clientTotal; i++) executorService.execute(() -> { try { update(); } catch (ParseException e) { e.printStackTrace(); } }); } }
參考地址:orm