SimpleDateFormat是線程不安全的類,通常不要定義爲static變量,若是定義爲static,必須經過加鎖等方式保證線程安全。java
例以下面一段代碼,啓動10個線程,同時使用一個SimpleDateFormat
實例去格式化Date
。git
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() {
@Override
public 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();
}
}
複製代碼
啓動之後拋出以下異常:spring
Exception in thread "Thread-5" Exception in thread "Thread-4" Exception in thread "Thread-0" java.lang.NumberFormatException: multiple points
at 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>() {
@Override
public 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線程不安全的問題。springboot