zoukankan      html  css  js  c++  java
  • 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);
    }
    }
  • 相关阅读:
    贝叶斯定理
    用matplotlib统计数据并画图
    词云图
    一行python代码能写出啥?
    用python生成二维码
    18个python的高效编程技巧
    django简介
    vue点击变色
    selenium破解人人登陆验证码
    selenium请求豆瓣网
  • 原文地址:https://www.cnblogs.com/coderdxj/p/11490773.html
Copyright © 2011-2022 走看看