IT评测·应用市场-qidao123.com技术社区

标题: Java中ThreadLocal的用法和原理 [打印本页]

作者: 丝    时间: 2023-4-12 13:24
标题: Java中ThreadLocal的用法和原理
用法

  1. package com.example.test1.service;
  2. import org.springframework.scheduling.annotation.Async;
  3. import org.springframework.stereotype.Component;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Date;
  6. @Component
  7. public class AsyncTest {
  8.     // 使用threadlocal管理
  9.     private static final ThreadLocal<SimpleDateFormat> dateFormatLocal =
  10.             ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
  11.     // 不用threadlocal进行管理,用于对比
  12.     SimpleDateFormat dateFormat = new SimpleDateFormat();
  13.     // 线程名称以task开头
  14.     @Async("taskExecutor")
  15.     public void formatDateSync(String format, Date date) throws InterruptedException {
  16.         SimpleDateFormat simpleDateFormat = dateFormatLocal.get();
  17.         simpleDateFormat.applyPattern(format);
  18.         
  19.         // 所有方法都可以直接使用这个变量,而不用根据形参传入
  20.         doSomething();
  21.         
  22.         Thread.sleep(1000);
  23.         System.out.println("sync " + Thread.currentThread().getName() +  " | " + simpleDateFormat.format(date));
  24.         
  25.         // 线程执行完毕,清除数据
  26.         dateFormatLocal.remove();
  27.     }
  28.     // 线程名称以task2开头
  29.     @Async("taskExecutor2")
  30.     public void formatDate(String format, Date date) throws InterruptedException {
  31.         dateFormat.applyPattern(format);
  32.         Thread.sleep(1000);
  33.         System.out.println("normal " + Thread.currentThread().getName() +  " | " + dateFormat.format(date));
  34.     }
  35. }
复制代码
使用junit进行测试:
[code]        @Test        void test2() throws InterruptedException {                for(int index = 1; index




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4