1、引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>2.14.5</version>
</dependency>
2、传递String参数
public class TransmittableThreadLocalDemo {
private static TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
public static void main(String[] args) {
// 在主线程中设置TransmittableThreadLocal的值
threadLocal.set("Hello, World!");
// 在新线程中获取TransmittableThreadLocal的值
Thread thread = new Thread(() -> {
String value = threadLocal.get();
System.out.println("TransmittableThreadLocal value in new thread: " + value);
});
thread.start();
}
}
3、传递对象
public class TransmittableThreadLocalDemo {
private static TransmittableThreadLocal<RequestContext> threadLocal = new TransmittableThreadLocal<>();
public static void main(String[] args) {
// 在主线程中设置TransmittableThreadLocal的值
RequestContext requestContext = new RequestContext();
requestContext.setUserId("123");
requestContext.setUserName("名字");
// 在新线程中获取TransmittableThreadLocal的值
Thread thread = new Thread(() -> {
String value = threadLocal.getRequestContext().getUserId();
System.out.println("TransmittableThreadLocal value in new thread: " + value);
});
thread.start();
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RequestContext(){
private String userId;
private String userName;
}
标签:String,thread,value,父子,threadLocal,线程,TransmittableThreadLocal,new
From: https://blog.csdn.net/weixin_47064437/article/details/141640432