ThreadLocal 解决simpledateformat线程不安全

SimpleDateFormat在多线程情况下会出现线程不安全的情况,故用ThreadLoacl 处理
/**
* 用ThreadLocal处理simplDateFormat线程不安全
*/
public class DateUtil {

public static SimpleDateFormat renderSimpleDateFormat(String pattern) {
ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern);
}
};
return threadLocal.get();
}


public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(10);
long start = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
String str = DateUtil.renderSimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
System.out.println(str);
countDownLatch.countDown();
}
}).start();
}
//TODO: await 不是 wait
countDownLatch.await();
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
posted @ 2019-09-09 11:42  洞玄巅峰  阅读(944)  评论(0编辑  收藏  举报