多線程編程八-父子線程怎麼共享數據(InheritableThreadLocal的使用)

前面文章中我們已經通過ThreadLocal來實現線程級別的數據共享。那麼如果子線程想訪問父線程的數據該怎麼做呢,InheritableThreadLocal可以幫助我們實現

1 InheritableThreadLocal的使用

測試代碼

private InheritableThreadLocal<Integer> inheritableThreadLocalData = new InheritableThreadLocal<>();

private ThreadLocal<Integer> threadLocalData = new ThreadLocal<>();

@Test
public void testInheritableThreadLocal() throws InterruptedException, ExecutionException {
    inheritableThreadLocalData.set(1);
    threadLocalData.set(1);
    System.out.println("current thread get InheritableThreadLocal data:" + inheritableThreadLocalData.get() +
            " get ThreadLocal data:" + threadLocalData.get());
    new Thread(() -> System.out.println("son thread get InheritableThreadLocal data:" + inheritableThreadLocalData.get() +
            " get ThreadLocal data:" + threadLocalData.get())).start();
}

輸出
current thread get InheritableThreadLocal data:1 get ThreadLocal data:1
son thread get InheritableThreadLocal data:1 get ThreadLocal data:null
可以看到當前內是可以訪問到ThreadLocal和InheritableThreadLocal的數據的
子線程只能訪問InheritableThreadLocal的數據,不能訪問ThreadLocal的數據

2 InheritableThreadLocal原理

InheritableThreadLocal繼承了ThreadLocal類,get、set方法用的都是父類的方法,只是重寫了getMap和createMap

ThreadLocalMap getMap(Thread t) {
   return t.inheritableThreadLocals;
}

void createMap(Thread t, T firstValue) {
    t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}

inheritableThreadLocals也是ThreadLocal.ThreadLocalMap對象,正常來說InheritableThreadLocal和ThreadLocal的功能完全一致的,那麼爲什麼前者可以獲取到父線程的值,後者不能呢?
我們看一下Thread的構造方法

public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}

直接跟到最下面

private void init(ThreadGroup g, Runnable target, String name,
                  long stackSize, AccessControlContext acc,
                  boolean inheritThreadLocals) {
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }

    this.name = name;

    Thread parent = currentThread();
    SecurityManager security = System.getSecurityManager();
    if (g == null) {
        /* Determine if it's an applet or not */

        /* If there is a security manager, ask the security manager
           what to do. */
        if (security != null) {
            g = security.getThreadGroup();
        }

        /* If the security doesn't have a strong opinion of the matter
           use the parent thread group. */
        if (g == null) {
            g = parent.getThreadGroup();
        }
    }

    /* checkAccess regardless of whether or not threadgroup is
       explicitly passed in. */
    g.checkAccess();

    /*
     * Do we have the required permissions?
     */
    if (security != null) {
        if (isCCLOverridden(getClass())) {
            security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
        }
    }

    g.addUnstarted();

    this.group = g;
    this.daemon = parent.isDaemon();
    this.priority = parent.getPriority();
    if (security == null || isCCLOverridden(parent.getClass()))
        this.contextClassLoader = parent.getContextClassLoader();
    else
        this.contextClassLoader = parent.contextClassLoader;
    this.inheritedAccessControlContext =
            acc != null ? acc : AccessController.getContext();
    this.target = target;
    setPriority(priority);
    if (inheritThreadLocals && parent.inheritableThreadLocals != null)
        this.inheritableThreadLocals =
            ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
    /* Stash the specified stack size in case the VM cares */
    this.stackSize = stackSize;

    /* Set thread ID */
    tid = nextThreadID();
}

關鍵就在這段代碼

// parent就是父線程,也就是執行new Thread()的線程
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
    this.inheritableThreadLocals =
        ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);


這裏會把父線程的inheritableThreadLocals賦值給子線程,從而實現了父子線程變量傳遞

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章