将一个对象从父线程传到子线程

package test;
/**
 * 使用InheritableThreadLocal 将父线程中的Integer对象传给子线程
 * @author xxzx
 *
 */
public class InheritableThreadLocalDemo {
     //final 可用volatile ,该对象的创建表示默认主线程创建了一条父线程
     private static   InheritableThreadLocal<Integer> intVal=new InheritableThreadLocal<Integer>();
     public static void main(String [] args) {
         Runnable rp = () ->{
             intVal.set(new Integer(10));
             Runnable rc=()->{
                 Thread thd=Thread.currentThread();
                 String name=thd.getName();
                 System.out.println(name+" "+intVal.get());
             };
             Thread thdChild =new Thread(rc);
             thdChild.setName("child");
             thdChild.start();
         };
         new Thread(rp).start();
        
     }
}

 代码说明:由于存储在本地变量中的值都是不相关的。当一个新的线程被创建出来,它就会获得一个新的包含initialValue()值的存储槽。

                   InheritableThreadLocal是 ThreadLocal的子类,除了定义一个InheritableThreadLocal()的构造方法,这个类还声明了下面的peotect()方法

                  T childValue(T parentValue):  在子线程被创建出来的时候用父线程的值作为参数计算出子线程的初始值,此方法会在子线程启动之前被调用

InheritableThreadLocal类的源代码如下(为了查看方面已删去部分注释):
package java.lang;
import java.lang.ref.*;

public class InheritableThreadLocal<T> extends ThreadLocal<T> {

    protected T childValue(T parentValue) {
        return parentValue;
    }

    /**
     * Get the map associated with a ThreadLocal.
     *
     * @param t the current thread
     */
    ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }

    /**
     * Create the map associated with a ThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the table.
     */
    void createMap(Thread t, T firstValue) {
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    }
}

 

转载于:https://www.cnblogs.com/pamne/p/11396490.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值