我正在嘗試ConcurrentHashMap使用多個執行緒測驗并發 put,但是處理后的映射大小不是我所期望的。
我有以下代碼可以將 1000 個條目插入ConcurrentHashMap:
@Test
public void testThreadSafetyConcurrentHashMap() {
Map<Integer, Integer> map = new ConcurrentHashMap<>();
Runnable runnable = () -> {
for (int i = 0; i < 1000; i ) {
map.put(i, i);
}
};
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i < 4; i ) {
executorService.submit(runnable);
}
System.out.println(map.size());
}
我期待 1000 個專案用于map.size()通話,但我不是每次都能收到。
有人可以告訴我問題是什么嗎?我以為4個執行緒同時放入1000個專案,最終會導致總共1000個專案?
uj5u.com熱心網友回復:
您可以使用它ExecutorService.invokeAll()來確保在檢查地圖大小之前所有執行緒都已完成其作業。
此方法回傳“所有完成時保存其狀態和結果的 Futures 串列”,即它是阻塞的,這就是我們在這種情況下需要的(我們對它的回傳值不感興趣,它在下面的代碼中被省略)。
invokeAll()需要一個集合,Callable我們可以使用Executors.callable()將 a 轉換Runnable為 a Callable。
Map<Integer, Integer> map = new ConcurrentHashMap<>();
Runnable runnable = () -> {
for (int i = 0; i < 1000; i ) {
map.put(i, i);
}
};
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.invokeAll(Collections.nCopies(4, Executors.callable(runnable)));
System.out.println(map.size());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/526394.html
