父子线程值传递
2019-10-14 本文已影响0人
CXY_XZL
1.问题描述
父子线程或线程池缓存线程复用时值未传递问题
2.解决方法
引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>2.11.0</version>
</dependency>
2.代码
public class CustomThreadLocal {
static ThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
static ExecutorService pool = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(2));
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
int j = i;
pool.execute(new Thread(()->{
CustomThreadLocal.threadLocal.set("xionger"+j);
new Service().call();
}));
}
}
static class Service{
void call(){
CustomThreadLocal.pool.execute(()->{
System.out.println(Thread.currentThread().getName()+"-service-"+CustomThreadLocal.threadLocal.get());
new Dao().call();});
}
}
static class Dao{
void call(){
System.out.println(Thread.currentThread().getName()+"-dao-"+CustomThreadLocal.threadLocal.get());
}
}
}
控制台:
pool-1-thread-1-service-xionger0
pool-1-thread-2-service-xionger1
pool-1-thread-2-dao-xionger1
pool-1-thread-1-dao-xionger0
由此可见,从Service
的call
方法成功将自定义线程的值传递到了Dao
类