Java中ThreadLocal的用法和原理

  金牌会员 | 2023-4-12 13:24:42 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 896|帖子 896|积分 2688

用法


  • 隔离各个线程间的数据
  • 避免线程内每个方法都进行传参,线程内的所有方法都可以直接获取到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
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表