hashmap是线程安全的吗?怎么解决?_解决SimpleDateFormat线程安全问题
生活随笔
收集整理的這篇文章主要介紹了
hashmap是线程安全的吗?怎么解决?_解决SimpleDateFormat线程安全问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SimpleDateFormat是線程不安全的類,一般不要定義為static變量,如果定義為static,必須通過加鎖等方式保證線程安全。
例如下面一段代碼,啟動10個線程,同時使用一個`SimpleDateFormat`實例去格式化`Date`。
```
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class SimpleDateFormatDemo {// (1)創建單例實例static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public static void test1() {// (2)創建多個線程,并啟動for (int i = 0; i < 10; ++i) {Thread thread = new Thread(new Runnable() {@Overridepublic void run() {try {// (3)使用單例日期實例解析文本System.out.println(sdf.parse("2019-03-07 15:17:27"));} catch (ParseException e) {e.printStackTrace();}}});thread.start();// (4)啟動線程}}public static void main(String[] args) {test1();}}```
啟動以后拋出如下異常:
```
Exception in thread "Thread-5" Exception in thread "Thread-4" Exception in thread "Thread-0" java.lang.NumberFormatException: multiple pointsat sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)at java.lang.Double.parseDouble(Double.java:538)at java.text.DigitList.getDouble(DigitList.java:169)at java.text.DecimalFormat.parse(DecimalFormat.java:2089)at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)at java.text.DateFormat.parse(DateFormat.java:364)at net.ijiangtao.tech.framework.spring.ispringboot.demo.demostart.thread.demo.SimpleDateFormatDemo$1.run(SimpleDateFormatDemo.java:18)```
怎么解決這個問題呢?下面推薦一種解決方案:
```
// (1)創建localDateFormat實例static ThreadLocal<DateFormat> localDateFormat = new ThreadLocal<DateFormat>() {@Overridepublic SimpleDateFormat initialValue() {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}};public static void test() {// (2)創建多個線程,并啟動for (int i = 0; i < 10; ++i) {Thread thread = new Thread(new Runnable() {public void run() {try {// (3)解析文本// System.out.println(sdf.parse("2019-03-07 15:17:27"));System.out.println(localDateFormat.get().parse("2019-03-07 15:17:27"));} catch (Exception e) {e.printStackTrace();}}});thread.start();// (4)啟動線程}}public static void main(String[] args) {test();}```
ThreadLocal,也叫做線程本地變量或者線程本地存儲,ThreadLocal為變量在每個線程中都創建了一個副本,那么每個線程可以訪問自己內部的副本變量,這樣就避免了SimpleDateFormat線程不安全的問題。
總結
以上是生活随笔為你收集整理的hashmap是线程安全的吗?怎么解决?_解决SimpleDateFormat线程安全问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安空调多少钱啊?
- 下一篇: python 列表算平均分_python