多线程SimpleDateFormat问题

 

at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)

1896处使用了NumberFormat与DateFormate产生联系使用。but确实作为一个全局变量去使用,于是内部属性也作为全局使用,多线程竞争产生了问题

 

优化方案:
1.使用1.8新的DataLocalTime解决这个问题
2.给每个线程增加个本地变量DateFormat

 

方案二:
 
package dubbo.wangbiao.project.ThreadDemo;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadLocalDemo {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");

    private static final ThreadLocal<DateFormat> dateFormatThreadLocal = new ThreadLocal<>();

    private static DateFormat getDateFormat() {
        DateFormat dateFormat = dateFormatThreadLocal.get();
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dateFormatThreadLocal.set(dateFormat);
        }
        return dateFormat;
    }

    public static Date prase(String dateStr) throws ParseException {
        Date parse = getDateFormat().parse(dateStr);
//        sdf.parse(dateStr)
        return parse;
    }
  public static   ExecutorService executorService = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 20; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                        System.out.println(prase("2020-05-18 20:20:20"));
                    } catch (InterruptedException | ParseException e) {
                        e.printStackTrace();
                    }
                }
            });
        }


        try {
            executorService.shutdown();
            boolean b = executorService.awaitTermination(3, TimeUnit.SECONDS);
            //b  线程执行时间小于等于设定的3s  true
            //b  线程执行时间打大于等于设定的3s  fasle
            if(!b){//3S
                System.out.println(" 到达指定时间,还有线程没执行完,不再等待,关闭线程池!");
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
            e.printStackTrace();
        }

    }
}

 

posted @ 2022-05-18 22:54  余生请多指教ANT  阅读(56)  评论(0编辑  收藏  举报