第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

請(qǐng)問(wèn)為什么不能直接使用一個(gè)Thread和Value綁定的Map?

請(qǐng)問(wèn)一下哈,自定義的ThreadLocal中,為什么不能直接聲明一個(gè)Map<Thread, T> 來(lái)保存value,而是要再套一個(gè)map?

正在回答

4 回答

秋田君說(shuō)的也很不錯(cuò), 我這里補(bǔ)充下, Map<Thread, T>這種結(jié)構(gòu),hash表沖突會(huì)很?chē)?yán)重,舉個(gè)例子。map.put(thread1, 100);map.put(thread1, 200);map.put(thread1, 300);你發(fā)現(xiàn)沒(méi)有,一個(gè)map put了三個(gè)值,那取值的時(shí)候, 怎么辦呢?

1 回復(fù) 有任何疑惑可以回復(fù)我~

同樣的 main 函數(shù),使用老師的代碼執(zhí)行會(huì)發(fā)現(xiàn)主線程不同 MyThreadLocal 實(shí)例中的數(shù)據(jù)是互不影響互不干擾的

public?static?void?main(String[]?args)?{
????MyThreadLocal<Long>?userIdContext?=?new?MyThreadLocal<>()?{
????????@Override
????????protected?Long?initialValue()?{
????????????return?1L;
????????}
????};
????MyThreadLocal<Connection>?connectionContext?=?new?MyThreadLocal<>();

????System.out.println(userIdContext.get());?//?1
????System.out.println(connectionContext.get());?//?null
}


1 回復(fù) 有任何疑惑可以回復(fù)我~

從使用上看應(yīng)該是為了不同場(chǎng)景使用時(shí)數(shù)據(jù)隔離,同一線程之間不同 MyThreadLocal 實(shí)例間的數(shù)據(jù)隔離

@Deprecated
public?class?MyThreadLocalWrong<T>?{

????private?static?Map<Thread,?Object>?threadLocalMap?=?new?HashMap<>();

????protected?T?initialValue()?{
????????return?null;
????}

????public?synchronized?T?get()?{
????????return?(T)?threadLocalMap.computeIfAbsent(Thread.currentThread(),?t?->?initialValue());
????}

????public?synchronized?void?set(T?t)?{
????????threadLocalMap.put(Thread.currentThread(),?t);
????}

????public?static?void?main(String[]?args)?{
????????MyThreadLocalWrong<Long>?userIdContext?=?new?MyThreadLocalWrong<>()?{
????????????@Override
????????????protected?Long?initialValue()?{
????????????????return?1L;
????????????}
????????};
????????MyThreadLocalWrong<Connection>?connectionContext?=?new?MyThreadLocalWrong<>();

????????System.out.println(userIdContext.get());?//?1
????????System.out.println(connectionContext.get());?//?1
????}
}

如果直接使用 Map<Thread, T> 來(lái)存儲(chǔ)數(shù)據(jù),由于 threadLocalMap 是靜態(tài)變量,那么同一線程不同 MyThreadLocal 實(shí)例存儲(chǔ)時(shí),數(shù)據(jù)會(huì)被覆蓋,讀取數(shù)據(jù)時(shí),會(huì)得到錯(cuò)亂的值!

5 回復(fù) 有任何疑惑可以回復(fù)我~

應(yīng)該為了解耦

0 回復(fù) 有任何疑惑可以回復(fù)我~

舉報(bào)

0/150
提交
取消

請(qǐng)問(wèn)為什么不能直接使用一個(gè)Thread和Value綁定的Map?

我要回答 關(guān)注問(wèn)題
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)