@Slf4j
@ThreadSafe
public class DateFormatExample4 {
public static int clientTotal = 5000;
public static int threadTotal = 200;
//线程封闭
private static final ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyyMMdd");
}
};
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
update();
semaphore.release();
} catch (InterruptedException e) {
e.getStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
}
public static void update(){
try {
simpleDateFormatThreadLocal.get().parse("20190107");
} catch (ParseException e) {
log.error("parse exception:{}",e);
}
}
}
老师您好,我用ThreadLocal修饰SimpleDateFormat这个,然后也不报错了。
但是请教了ThreadLocal的用法,发现他不是为了解决线程安全设计的。
那这里使用之后,这个不报错了,解决了线程安全的问题吗?