立即学习:https://edu.csdn.net/course/play/26270/326865?utm_source=blogtoedu
ThreadLocal定义
ThreadLocal为解决多线程程序的并发问题提供了一种新的思路。使用这个工具类可以很简洁地编写出优美的多线程程序,ThreadLocal并不是一个Thread,而是Thread的局部变量。
如何使用?程序怎么写?
模拟场景:HTTP服务端使用多线程处理来自不同用户的请求(没使用)
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class D1 {
public static void main(String[] args) {
sampleTest();
}
private static void sampleTest(){
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(()->{
Long userId = 10000L;
doUseRequest(userId);
});
executorService.submit(()->{
Long userId = 20000L;
doUseRequest(userId);
});
}
private static void doUseRequest(Long userId){
ThreadContext threadContext = new ThreadContext();
threadContext.setUserId(userId);
Long info = getMyInfo(threadContext);
List<Long> myCourses = getMyCourses(threadContext);
System.out.println("info="+info+";"+"courses="+myCourses);
}
private static Long getMyInfo(ThreadContext threadContext){
return threadContext.getUserId();
}
private static List<Long> getMyCourses(ThreadContext threadContext){
return Collections.singletonList(threadContext.getUserId());
}
public static class ThreadContext{
private Long userId;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}
}
总结:不使用ThreadLocal时,需在整个上下文调用的方法中将关键字参数透传
存在的问题:
·代码整洁度不高
·如果某处透传时将参数值改掉或设置为null,后续调用方法中用到这个参数的代码会受到影响