`

线程安全的SimpleDateFormat

阅读更多
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutionException;

public class ThreadTest {

    //要在高并发环境下能有比较好的体验,可以使用ThreadLocal来限制SimpleDateFormat只能在线程内共享,这样就避免了多线程导致的线程安全问题。
    private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    /**
     * 同一个map里面存储了各个水果的数量,
     *
     * @param args
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // #1. Date-->字符串
        String dts = threadLocal.get().format(new Date());
        System.out.println(dts);

        // #2.字符串-->Date
        try {
            System.out.println(threadLocal.get().parse("2015-06-06 06:00:00").getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics