zoukankan      html  css  js  c++  java
  • 《Java多线程编程核心技术》读后感(十三)

    类InheritableThreadLocal的使用

    使用类InheritableThreadLocal可以在子线程中取得父线程继承下来的值

    值继承

    package Third;
    
    import java.util.Date;
    
    public class InheritableThreadLocalExt extends InheritableThreadLocal {
        @Override
        protected Object initialValue() {
            return new Date().getTime();
        }
    }
    package Third;
    
    public class Tools {
        public static InheritableThreadLocalExt tl = new InheritableThreadLocalExt();
    }
    package Third;
    
    public class ThreadA extends Thread {
    
        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println("在ThreadA线程中取值=" + Tools.tl.get());
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    
    }
    package Third;
    
    public class Run {
    
        public static void main(String[] args) {
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println("       在Main线程中取值=" + Tools.tl.get());
                    Thread.sleep(100);
                }
                Thread.sleep(5000);
                ThreadA a = new ThreadA();
                a.start();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    }

    值继承再修改

    基于上面的修改

    package Third;
    
    import java.util.Date;
    public class InheritableThreadLocalExt extends InheritableThreadLocal {
        @Override
        protected Object initialValue() {
            return new Date().getTime();
        }
    
        @Override
        protected Object childValue(Object parentValue) {
            return parentValue + " 我在子线程加的~!";
        }
    }

    注意:如果子线程在取得值的同时,主线程将InheritableThreadLocal 中的值进行更改,那么子线程取到的值还是旧值

  • 相关阅读:
    Redis
    多线程相关
    selenium操作浏览器的基本方法
    selenium之 webdriver与三大浏览器版本映射表(更新至v2.29)
    selenium安装及官方文档
    Python(3)_python对Json进行操作
    python类中的self参数和cls参数
    python3中shuffle函数
    Python3中assert断言
    python2和python3中range的区别
  • 原文地址:https://www.cnblogs.com/Michael2397/p/7858142.html
Copyright © 2011-2022 走看看