Java 多线程学习笔记(十) InheritableThreadLocal的使用

来源:互联网 发布:机票数据 编辑:程序博客网 时间:2024/05/16 12:26

废话少说,上代码

package extthread;import tools.Tools;public class ThreadA extends Thread {@Overridepublic 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 blocke.printStackTrace();}}}

package ext;import java.util.Date;public class InheritableThreadLocalExt extends InheritableThreadLocal {@Overrideprotected Object initialValue() {return new Date().getTime();}}
package test;import tools.Tools;import extthread.ThreadA;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 tools;import ext.InheritableThreadLocalExt;public class Tools {public static InheritableThreadLocalExt tl = new InheritableThreadLocalExt();}


子线程可以从父线程中去值。值继承也可以在修改。见如下代码

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


运行结果:

       在Main线程中取值=1467603826045
       在Main线程中取值=1467603826045
       在Main线程中取值=1467603826045
       在Main线程中取值=1467603826045
       在Main线程中取值=1467603826045
       在Main线程中取值=1467603826045
       在Main线程中取值=1467603826045
       在Main线程中取值=1467603826045
       在Main线程中取值=1467603826045
       在Main线程中取值=1467603826045
在ThreadA线程中取值=1467603826045 我在子线程加的~!
在ThreadA线程中取值=1467603826045 我在子线程加的~!
在ThreadA线程中取值=1467603826045 我在子线程加的~!
在ThreadA线程中取值=1467603826045 我在子线程加的~!
在ThreadA线程中取值=1467603826045 我在子线程加的~!
在ThreadA线程中取值=1467603826045 我在子线程加的~!
在ThreadA线程中取值=1467603826045 我在子线程加的~!
在ThreadA线程中取值=1467603826045 我在子线程加的~!
在ThreadA线程中取值=1467603826045 我在子线程加的~!
在ThreadA线程中取值=1467603826045 我在子线程加的~!



2 0
原创粉丝点击