• 《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详解
    Linux常用命令
    sqlserver 游标写法
    Flask总结
    HTTPS协议
    Django REST framework 简介
    Cookie和session
    利用rest-framework编写逻辑关系
    vuex
    jQuery和Bootstrap的优点
  • 原文地址:https://www.cnblogs.com/Michael2397/p/7858142.html
Copyright © 2020-2023  润新知