java.lang.Number FormatException:multiple points問題

8321 ワード

このような問題は主にSimpleDateFormatがマルチスレッド環境においてスレッドが安全でないため、複数スレッド環境においてSimpleDateFormatの例を共有した場合、例えば、類似の日付クラスにおいてグローバルSimpleDateFormatオブジェクトを定義した場合、上記のエラーが発生します。例えば、あなたのコードはこのようなものです。
package com.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;
    }
}
上記のコードであれば、マルチスレッド環境では、タイトルのようなエラーが発生する可能性があります。解決方法1、各方法の中でnewの新しいSimpleDateFormatオブジェクトを提案します。このようにすればこの問題を回避できます。2、スレッドのローカル変数を保存するThreadLocalオブジェクトを使用して、各スレッドのSimpleDateFormatオブジェクトを保存することもできます。小編は主に第二種類の使用について話し、上記のコードに対して変更します。
package com.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 *
 * @author Administrator
 *
 */
public class DateUtils {

private static final String format = "yyyy-MM-dd";

    //     
    private static final ThreadLocal<SimpleDateFormat> threadLocal = new
            ThreadLocal<SimpleDateFormat>();

    public static Date covertDateStrToDate(String dateStr){
        SimpleDateFormat sdf = null;
        sdf = threadLocal.get();
        if (sdf == null){
            sdf = new SimpleDateFormat(format);
        }
        //
        Date date = null;
        try {
            System.out.println("     :" + Thread.currentThread().getName());
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }
}
はい、問題は解決して、マルチスレッド環境の下で、変数を共有するスレッドの安全問題に注意してください。特に必要がないなら、静的公共変数を勝手に定義しないでください。