java.lang.NumberFormatException: multiple points問題


一般這種問題主要是因為SimpleDateFormat在多線程環境下,是線程不安全的,所以如果你在多線程環境中共享了SimpleDateFormat的實例,比如你在類似日期類中定義了一個全局的SimpleDateFormat對象,這樣子肯定會出現上述的報錯,比如你的代碼是這樣的

 1 package com.yongcheng.liuyang.utils;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 /**
 8  *
 9  * 
10  * @author Administrator
11  *
12  */
13 public class DateUtils {
14 
15     private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
16     
17     public static Date covertDateStrToDate(String dateStr){
18         
19         try {
20             return format.parse(dateStr);
21         } catch (ParseException e) {
22             e.printStackTrace();
23         }
24         return null;
25     }
26 }

如果是上述代碼,那么在多線程環境下,你可能會收到如標題所示的錯誤。

解決辦法

1、建議在每個方法中都new一個新的SimpleDateFormat對象,這樣子就可以避免這種問題。

2、也可以使用保存線程局部變量的ThreadLocal對象來保存每一個線程的SimpleDateFormat對象,小編主要說說第二種的使用,針對上述代碼做的改變。

 1 package com.yongcheng.liuyang.utils;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 /**
 8  *
 9  * 
10  * @author Administrator
11  *
12  */
13 public class DateUtils {
14 
15 private static final String format = "yyyy-MM-dd";
16     
17     //每一個線程
18     private static final ThreadLocal<SimpleDateFormat> threadLocal = new 
19             ThreadLocal<SimpleDateFormat>();
20     
21     public static Date covertDateStrToDate(String dateStr){
22         SimpleDateFormat sdf = null;
23         sdf = threadLocal.get();
24         if (sdf == null){
25             sdf = new SimpleDateFormat(format);
26         }
27         //
28         Date date = null;
29         try {
30             System.out.println("當前線程為:" + Thread.currentThread().getName());
31             date = sdf.parse(dateStr);
32         } catch (ParseException e) {
33             e.printStackTrace();
34         }
35         
36         return date;
37     }
38 }

好了,問題解決,在多線程環境下,一定要注意共享變量的線程安全問題,如無特殊必要,建議不要隨便定義靜態公共變量,如果非要定義,建議考慮好多線程的問題!

package com.yongcheng.liuyang.utils;
import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;
/** * *  * @author Administrator * */public class DateUtils {
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");public static Date covertDateStrToDate(String dateStr){try {return format.parse(dateStr);} catch (ParseException e) {e.printStackTrace();}return null;}}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM