用法
- 隔离各个线程间的数据
- 避免线程内每个方法都进行传参,线程内的所有方法都可以直接获取到ThreadLocal中管理的对象。
- package com.example.test1.service;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.stereotype.Component;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- @Component
- public class AsyncTest {
- // 使用threadlocal管理
- private static final ThreadLocal<SimpleDateFormat> dateFormatLocal =
- ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
- // 不用threadlocal进行管理,用于对比
- SimpleDateFormat dateFormat = new SimpleDateFormat();
- // 线程名称以task开头
- @Async("taskExecutor")
- public void formatDateSync(String format, Date date) throws InterruptedException {
- SimpleDateFormat simpleDateFormat = dateFormatLocal.get();
- simpleDateFormat.applyPattern(format);
-
- // 所有方法都可以直接使用这个变量,而不用根据形参传入
- doSomething();
-
- Thread.sleep(1000);
- System.out.println("sync " + Thread.currentThread().getName() + " | " + simpleDateFormat.format(date));
-
- // 线程执行完毕,清除数据
- dateFormatLocal.remove();
- }
- // 线程名称以task2开头
- @Async("taskExecutor2")
- public void formatDate(String format, Date date) throws InterruptedException {
- dateFormat.applyPattern(format);
- Thread.sleep(1000);
- System.out.println("normal " + Thread.currentThread().getName() + " | " + dateFormat.format(date));
- }
- }
复制代码 使用junit进行测试:
[code] @Test void test2() throws InterruptedException { for(int index = 1; index |