美文网首页程序员
父子线程值传递问题,ThreadLocal存储值变化

父子线程值传递问题,ThreadLocal存储值变化

作者: zhangweisep | 来源:发表于2020-03-17 15:03 被阅读0次

    此处引用了alibaba线程池来解决父子线程间传值及线程池使用后无法初始化问题

    public static void main(String[] args) throws InterruptedException {
            //创建父线程
            //做测试时注意观察ThreadLocal存储的值的变化
            final ThreadLocal<String> objectThreadLocal = new TransmittableThreadLocal<>();
            //final ThreadLocal<String> objectThreadLocal = new ThreadLocal<>();
            objectThreadLocal.set("测试");
            //创建一个线程运行实例
            Runnable runnable = () -> {
                System.out.println("-------------------------------------------------");
                System.out.println("修改前" + Thread.currentThread() + ": " + objectThreadLocal.get());
                objectThreadLocal.set("111111");
                System.out.println("修改后" + Thread.currentThread() + ": " + objectThreadLocal.get());
                System.out.println("-----------------------------------------------------");
            };
    
            /*new Thread(runnable).start();
            TimeUnit.SECONDS.sleep(1);
            new Thread(runnable).start();
            TimeUnit.SECONDS.sleep(1);
            new Thread(runnable).start();
            TimeUnit.SECONDS.sleep(1);*/
            //创建线程池
            ExecutorService executorService = Executors.newFixedThreadPool(1);
            //普通使用方式
            //executorService.submit(new Thread(runnable));
            //TimeUnit.SECONDS.sleep(1);
            //executorService.submit(new Thread(runnable));
            //TimeUnit.SECONDS.sleep(1);
            //executorService.submit(new Thread(runnable));
            //TimeUnit.SECONDS.sleep(1);
    
            //使用TtlRunnable包装Runnable
            TtlRunnable ttlRunnable = TtlRunnable.get(runnable);
            //执行线程实例-1
            executorService.submit(ttlRunnable);
            //设置等待时间
            TimeUnit.SECONDS.sleep(1);
            //执行线程实例-2
            executorService.submit(ttlRunnable);
            //设置等待时间
            TimeUnit.SECONDS.sleep(1);
            //执行线程实例-3
            executorService.submit(ttlRunnable);
            //设置等待时间
            TimeUnit.SECONDS.sleep(1);
            
            System.out.println(Thread.currentThread() + ": "+objectThreadLocal.get());
            //强制程序运行以查看相应状态
            executorService.shutdown();
    
        }
    

    相关文章

      网友评论

        本文标题:父子线程值传递问题,ThreadLocal存储值变化

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