1. 程式人生 > >Java多線程(三)SimpleDateFormat

Java多線程(三)SimpleDateFormat

spa bsp sdf java多線程 ext add println turn static

多線程報錯:java.lang.NumberFormatException: multiple points

SimpleDateFormat是非線程安全的,在多線程情況下會有問題,在每個線程下得各自new SimpleDateFormat()就可以了

實現有兩種方法:

1.

public class DateTools {

    public static Date parse(String formatPattern,String dateString) throws ParseException{
        return new SimpleDateFormat(formatPattern).parse(dateString);
    }
    
    
public static String format(String formatPattern,Date date){ System.out.println("format"); return new SimpleDateFormat(formatPattern).format(date); } }

2. ThreadLocal 每個線程都有自己的私有數據

package threadDemo.date;

import java.text.SimpleDateFormat;

public class DateTools {

    
private static ThreadLocal<SimpleDateFormat> threadLocals = new ThreadLocal<SimpleDateFormat>(); public static SimpleDateFormat getSimpleDateFormat(String datePattern){ SimpleDateFormat sdf = null; sdf = threadLocals.get(); if(sdf ==null){ sdf
= new SimpleDateFormat(datePattern); threadLocals.set(sdf); } return sdf; } }

Java多線程(三)SimpleDateFormat