![](https://img2022.cnblogs.com/blog/1501092/202205/1501092-20220518215153352-1925709473.png)
![](https://img2022.cnblogs.com/blog/1501092/202205/1501092-20220518215138208-1894956880.png)
![](https://img2022.cnblogs.com/blog/1501092/202205/1501092-20220518215142163-518216585.png)
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();
}
}
}