类InheritableThreadLocal的使用

来源:互联网 发布:速读训练软件安卓版 编辑:程序博客网 时间:2024/06/05 15:29

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

看栗子:

public class Tools {    public static InheritableThreadLocalExt t1=new InheritableThreadLocalExt();}

public class InheritableThreadLocalExt extends InheritableThreadLocal{    @Override    protected Object initialValue() {        return new Date().getTime();    }}

public class ThreadA extends Thread{    @Override    public void run() {        try{            for(int i=0;i<10;i++){                System.out.println("在ThreadA线程中取值 ="+Tools.t1.get());                Thread.sleep(100);            }        }catch (InterruptedException e){            e.printStackTrace();        }    }}
public class Run {    public static void main(String[] args){        try{            for(int i=0;i<10;i++){                System.out.println(" 在Main线程中取值="+Tools.t1.get());                Thread.sleep(100);            }            Thread.sleep(5000);            ThreadA a=new ThreadA();            a.start();        }catch (InterruptedException e){            e.printStackTrace();        }    }}
可以通过重写childValue方法在继承的同时对值进行进一步的处理

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






阅读全文
0 0
原创粉丝点击