成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

ThreadLocal和InheritableThreadLocal詳解

開發 后端
為了方便且更加安全的進行多線程編程,jdk引入ThreadLocal和InheritableThreadLocal兩個類,以供開發人員進行多線程之間的數據傳遞和數據共享。InheritableThreadLocal是ThreadLocal的子類,它可以實現子線程共享父線程的變量。

一、概述

為了方便且更加安全的進行多線程編程,jdk引入ThreadLocal和InheritableThreadLocal兩個類,以供開發人員進行多線程之間的數據傳遞和數據共享。InheritableThreadLocal是ThreadLocal的子類,它可以實現子線程共享父線程的變量。

二、案例介紹

ThreadLocal:

private static ThreadLocal<String> testThreadLocal = new ThreadLocal<>();
/*
// 創建時可重寫初始化方法
ThreadLocal<String> testThreadLocal = new ThreadLocal<String>(){
    public Connection initialValue(){
        return "zhangsan";
    }
};
*/

public static void main(String[] args) {
        // 設置線程變量
        testThreadLocal.set("zhangsan");
        // 獲取線程變量
        String userName = testThreadLocal.get();
        System.out.println("userName: " + userName);
        // 刪除線程變量
        testThreadLocal.remove();
        userName = testThreadLocal.get();
        System.out.println("userName: " + userName);
}
#結果輸出
userName: zhangsan
userName: null
public static void main(String[] args) {
        // 主線程
        testThreadLocal.set("zhangsan");
        System.out.println("userName0: " + testThreadLocal.get());
        // 線程1
        new Thread(() -> {
            testThreadLocal.set("lisi");
            System.out.println("userName1: " + testThreadLocal.get());
        }).start();

        // 線程2
        new Thread(() -> {
            testThreadLocal.set("wangwu");
            System.out.println("userName2: " + testThreadLocal.get());
        }).start();
}
#結果輸出【線程之間變量相關隔離】
userName0: zhangsan
userName1: lisi
userName2: wangwu

接下來看下set方法:

public void set(T value) {
    // 獲取當前線程(調用方線程:主線程、線程1......)
    Thread t = Thread.currentThread();
    // 當前線程作為key,獲取對應的線程變量ThreadLocalMap
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        // 設置線程變量:key為當前定義的ThreadLocal實例的this引用,值為我們傳入的數據
        map.set(this, value);
    } else {
        // 第一次設置線程變量,則會創建ThreadLocalMap
        createMap(t, value);
    }    
}

再看下get方法:

public T get() {
    // 獲取當前線程(調用方線程:主線程、線程1......)
    Thread t = Thread.currentThread();
    // 當前線程作為key,獲取對應的線程變量ThreadLocalMap
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        // 值最終是存在Entry對象的value屬性
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            T result = (T)e.value;
            return result;
        }
    }
    // ThreadLocalMap為空,則初始化操作
    return setInitialValue();
}
 
private T setInitialValue() {
    // 創建ThreadLocal時可重寫初始化方法
    T value = initialValue();
    // 獲取當前線程(調用方線程:主線程、線程1......)
    Thread t = Thread.currentThread();
    // 當前線程作為key,獲取對應的線程變量ThreadLocalMap
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        // 設置線程變量:key為當前定義的ThreadLocal實例的this引用,值為初始化方法返回的數據
        map.set(this, value);
     } else {
        // 第一次設置線程變量,則會創建ThreadLocalMap
        createMap(t, value);
     }    
    return value;
}

InheritableThreadLocal:

private static InheritableThreadLocal<String> testInheritableThreadLocal = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        // 主線程
        testInheritableThreadLocal.set("zhangsan");
        System.out.println("userName0: " + testInheritableThreadLocal.get());
        
        // 線程1
        new Thread(() -> System.out.println("userName1: " + testInheritableThreadLocal.get())).start();

        // 線程2
        new Thread(() -> System.out.println("userName2: " + testInheritableThreadLocal.get())).start();
    }
#結果輸出
userName0: zhangsan
userName1: zhangsan
userName2: zhangsan

查看InheritableThreadLocal的源碼:

public class InheritableThreadLocal<T> extends ThreadLocal<T> {
 
    protected T childValue(T parentValue) {
        return parentValue;
    }
   
    ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }

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

InheritableThreadLocal繼承了ThreadLocal類型,并且重寫了getMap和createMap方法,唯一的區別是:threadLocals(ThreadLocalMap類型)變成了inheritableThreadLocals(ThreadLocalMap類型)。

查看get方法:

public T get() {
        Thread t = Thread.currentThread();
        // 注意:InheritableThreadLocal重寫了getMap方法,返回inheritableThreadLocals
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

查看inheritableThreadLocals設置的地方,最終定位到java.lang.Thread#init方法:

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) {
            if (security != null) {
                g = security.getThreadGroup();
            }
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }
        g.checkAccess();
        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)
           // 將父線程inheritableThreadLocals復制給子線程inheritableThreadLocals
           // 此處可聯想到:如果使用了線程池,而線程池中的線程是復用的,不會再次調用初始化方法
           // 所以無法將父線程inheritableThreadLocals復制給子線程inheritableThreadLocals
            this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        this.stackSize = stackSize;
        tid = nextThreadID();
    }

三、注意事項

  • 使用ThreadLocal、或者InheritableThreadLocal方法時,注意及時調用remove方法進行清理。
  • 注意線程池結合InheritableThreadLocal的使用,線程池中的線程是復用的,不會再次調用初始化方法,所以無法將父線程inheritableThreadLocals復制給子線程inheritableThreadLocals。
責任編輯:姜華 來源: 今日頭條
相關推薦

2015-09-09 08:45:49

JavaThreadLocal

2024-10-15 17:12:38

代碼父子線程開源

2022-11-14 09:13:16

2023-02-28 11:27:50

線程處理解決共享變量

2024-08-13 15:07:20

2021-02-09 09:51:58

異步傳遞數據

2024-10-28 08:15:32

2018-04-09 08:17:36

線程ThreadLocal數據

2021-05-26 08:02:03

ThreadLocal多線程多線程并發安全

2023-09-22 17:34:37

內存remove方法

2025-06-27 07:19:48

2009-09-29 17:11:23

Hibernate T

2011-07-14 13:50:09

ThreadLocal

2021-09-13 15:17:52

FastThreadL源碼Java

2021-01-19 05:24:36

ThreadLocal線程編程

2021-05-06 08:55:24

ThreadLocal多線程多線程并發安全

2023-08-02 08:54:58

Java弱引用鏈表

2022-05-11 07:36:12

Java線程安全

2024-07-09 08:35:09

2011-07-14 14:15:40

ThreadLocal
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 天天看夜夜 | 毛片链接| 黄色网毛片 | 亚洲一区中文字幕 | 狠狠干天天干 | 中文字幕一区二区三区在线观看 | 精品二 | 欧美国产日韩一区二区三区 | 国产精品国产精品国产专区不片 | 天天天久久久 | 国产高潮av| 亚洲性爰 | 亚洲一区二区三区视频 | 91福利在线观看 | 一级黄色毛片免费 | 国产欧美一级 | 91色在线 | 精品综合久久久 | 午夜看看 | 日韩精品免费看 | 夜夜骑首页| 国产99在线 | 欧美 | 欧美日韩中文在线观看 | 亚洲一区 中文字幕 | 久久婷婷国产香蕉 | 国产高清久久久 | 欧美日本亚洲 | 欧美成人免费在线视频 | 不卡在线视频 | 超碰人人人 | 日韩三区在线 | 天天干视频在线 | 日本网站免费在线观看 | 亚洲二区在线观看 | 男人午夜视频 | 欧洲一级视频 | 91av国产在线视频 | 日韩波多野结衣 | 国产免费一区 | 精品久久久久久 | 欧美lesbianxxxxhd视频社区 |