package com.aynu.util;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* @author xiaolang
* @description: ThreadLocalUtil
* @date 2022/3/25 14:49
*/
@Data
public class ThreadLocalUtil {
private static ThreadLocal<List<String>> thread1 = new ThreadLocal<List<String>>() {
@Override
protected synchronized List<String> initialValue() {
return new ArrayList<>();
}
};
private static ThreadLocal<List<String>> thread2 = new ThreadLocal<List<String>>() {
@Override
protected synchronized List<String> initialValue() {
return new ArrayList<>();
}
};
/**
* InheritableThreadLocal可以让子线程获取到父线程的ThreadLocal
*/
private static ThreadLocal<List<String>> thread3 = new InheritableThreadLocal<List<String>>() {
@Override
protected synchronized List<String> initialValue() {
return new ArrayList<>();
}
};
public static List<String> getThread1() {
return thread1.get();
}
public static void setThread1(List<String> list) {
thread1.set(list);
}
public static List<String> getThread2() {
return thread2.get();
}
public static void setThread2(List<String> list) {
thread2.set(list);
}
public static List<String> getThread3() {
return thread3.get();
}
public static void setThread3(List<String> list) {
thread3.set(list);
}
public static void main(String[] args) throws InterruptedException {
ArrayList<String> list = new ArrayList<>();
list.add("Thread1");
ThreadLocalUtil.setThread1(list);
List<String> thread1 = ThreadLocalUtil.getThread1();
System.out.println("父线程Thread1 = " + thread1);
new Thread(() -> {
List<String> childTradeDataMap = ThreadLocalUtil.getThread1();
System.out.println("子线程tradeDataMap = " + childTradeDataMap);
}).start();
Thread.sleep(2000);
System.out.println("================================== = ");
ArrayList<String> list2 = new ArrayList<>();
list2.add("Thread2");
ThreadLocalUtil.setThread2(list2);
List<String> thread2 = ThreadLocalUtil.getThread2();
System.out.println("thread2 = " + thread2);
System.out.println("父线程Thread1 = " + ThreadLocalUtil.getThread1());
System.out.println("================================== = ");
ArrayList<String> list3 = new ArrayList<>();
list3.add("Thread3");
ThreadLocalUtil.setThread3(list3);
List<String> thread3 = ThreadLocalUtil.getThread3();
System.out.println("父线程thread3 = " + thread3);
new Thread(() -> {
List<String> thread31 = ThreadLocalUtil.getThread3();
System.out.println("子线程thread3 = " + thread31);
}).start();
Thread.sleep(2000);
}
}
要点:
1.每个线程有自己的ThreadLocal
2.子线程可以拿到父线程的ThreadLocal
3.用完要remove一下
例子:
在controller中先设置再获取
有的小伙伴就要问了,哎呀,我根本拿不到值,你这不是坑人吗?
每个人进来请求都是单独的一个线程,我们稍微设置一下很容易就看到我们设置的值了