3.4.1在子线程中取父线程的值(InheritableThreadLocal)

来源:互联网 发布:deepin15 linux 教程 编辑:程序博客网 时间:2024/05/29 18:09

package demo;import java.util.Date;/** * Created by sunyifeng on 17/10/18. */public class InheritableThreadLocalExt extends InheritableThreadLocal {    @Override    protected Object initialValue() {        return new Date().getTime();    }    @Override    protected Object childValue(Object parentValue) {        return parentValue + "我在子线程中加的";    }}
package demo;/** * Created by sunyifeng on 17/10/18. */public class Tools {    public static InheritableThreadLocalExt inheritableThreadLocalExt = new InheritableThreadLocalExt();}
package demo;/** * Created by sunyifeng on 17/10/18. */public class MyThread extends Thread {    @Override    public void run() {        try {            for (int i = 0; i < 10; i++) {                System.out.println("在线程A中取值=" + Tools.inheritableThreadLocalExt.get());                Thread.sleep(100);            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
package demo;/** * Created by sunyifeng on 17/10/18. */public class Run {    public static void main(String[] args) {        try {            for (int i = 0; i < 10; i++) {                System.out.println("在main线程中取值=" + Tools.inheritableThreadLocalExt.get());                Thread.sleep(100);            }            Thread.sleep(5000);            MyThread myThread = new MyThread();            myThread.start();        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
运行结果:

在main线程中取值=1508261472693
在main线程中取值=1508261472693
在main线程中取值=1508261472693
在main线程中取值=1508261472693
在main线程中取值=1508261472693
在main线程中取值=1508261472693
在main线程中取值=1508261472693
在main线程中取值=1508261472693
在main线程中取值=1508261472693
在main线程中取值=1508261472693
在线程A中取值=1508261472693我在子线程中加的
在线程A中取值=1508261472693我在子线程中加的
在线程A中取值=1508261472693我在子线程中加的
在线程A中取值=1508261472693我在子线程中加的
在线程A中取值=1508261472693我在子线程中加的
在线程A中取值=1508261472693我在子线程中加的
在线程A中取值=1508261472693我在子线程中加的
在线程A中取值=1508261472693我在子线程中加的
在线程A中取值=1508261472693我在子线程中加的
在线程A中取值=1508261472693我在子线程中加的

程序分析:

1、子线程可以通过继承取父类的值,通过InheritableThreadLocal实行;

2、如果主线程更改InheritableThreadLocal的值,子线程还是取原来的值。


阅读全文
0 0