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

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

public static void main(String[] args) throws InterruptedException {
        //创建父线程
        //做测试时注意观察ThreadLocal存储的值的变化
        final ThreadLocal objectThreadLocal = new TransmittableThreadLocal<>();
        //final ThreadLocal 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存储值变化)