美文网首页
父子线程值传递

父子线程值传递

作者: CXY_XZL | 来源:发表于2019-10-14 15:51 被阅读0次

    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
    

    由此可见,从Servicecall方法成功将自定义线程的值传递到了Dao

    相关文章

      网友评论

          本文标题:父子线程值传递

          本文链接:https://www.haomeiwen.com/subject/lxprmctx.html