0
点赞
收藏
分享

微信扫一扫

类InheritableThreadLocal的使用


使用类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 条评论