ThreadLocal使用模板

class ThreadLocalTest {
     

    private static final Logger logger = LoggerFactory.getLogger(ThreadLocalTest.class);

    private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>() {
     
        @Override
        protected DateFormat initialValue() {
     
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private static final ThreadLocal<Map<String, Object>> mapThreadLocal = new ThreadLocal<Map<String, Object>>() {
     
        @Override
        protected Map<String, Object> initialValue() {
     
            return new HashMap<>(16);
        }
    };

    public static void main(String[] args) {
     
        for (int i = 0; i < 10; i++) {
     
            new Thread(() -> {
     
                DateFormat dateFormat = format.get();
                String format = dateFormat.format(new Date());
                logger.info("当前时间:{}", format);
            }, "dateFormat-" + i).start();
        }

        System.out.println("------------------");

        for (int i = 0; i < 10; i++) {
     
            new Thread(() -> {
     
                Map<String, Object> stringObjectMap = mapThreadLocal.get();
                stringObjectMap.put(Thread.currentThread().getName(), Thread.currentThread().getId());
                stringObjectMap.forEach((k, v) ->
                        logger.info("{} --- {}", k, v)
                );
            }, "map-" + i).start();
        }
    }

}

你可能感兴趣的:(java)