多线程SimpleDateFormate问题
作者:互联网
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869) 1896处使用了NumberFormat与DateFormate产生联系使用。but确实作为一个全局变量去使用,于是内部属性也作为全局使用,多线程竞争产生了问题
优化方案: 1.使用1.8新的DataLocalTime解决这个问题 2.给每个线程增加个本地变量DateFormat
方案二: 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(200); System.out.println(prase("2020-05-18 20:20:20")); } catch (InterruptedException | ParseException e) { e.printStackTrace(); } } }); } executorService.shutdown(); boolean b = executorService.awaitTermination(3, TimeUnit.SECONDS); }
标签:executorService,20,dateFormat,SimpleDateFormate,SimpleDateFormat,问题,static,new,多 来源: https://www.cnblogs.com/wangbiaohistory/p/16286732.html