一、介紹
1、Java 5.0 在 java.util.concurrent 包中提供了多種併發容器類來改進同步容器 的性能。
2、 ConcurrentHashMap 同步容器類是Java 5 增加的一個線程安全的哈希表。對 與多線程的操作,介於 HashMap 與 Hashtable 之間。內部採用“鎖分段” 機制替代 Hashtable 的獨佔鎖。進而提高性能。
3、 java.util.concurrent包還提供了設計用於多線程上下文中的 Collection 實現:
- ConcurrentHashMap、ConcurrentSkipListMap、ConcurrentSkipListSet、 CopyOnWriteArrayList 和 CopyOnWriteArraySet。
- 當期望許多線程訪問一個給 定 collection 時,ConcurrentHashMap 通常優於同步的 HashMap, ConcurrentSkipListMap 通常優於同步的 TreeMap。
- 當期望的讀數和遍歷遠遠 大於列表的更新數時,CopyOnWriteArrayList 優於同步的 ArrayList。
二、代碼使用
package com.example.juc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author haoxiansheng
*/
public class CopyOnWriteArrayListTest {
public static void main(String[] args) {
HelloThread helloThread = new HelloThread();
for (int i = 0; i < 10; i++) {
new Thread(helloThread).start();
}
}
}
class HelloThread implements Runnable {
//private static List<String> list = Collections.synchronizedList(new ArrayList<>());
/**
* CopyOnWriteArrayList 適合讀多寫少 併發場景
* 添加操作多時效率低,因爲每次都會進行復制,開銷非常的大
*/
private static CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
static {
list.add("aa");
list.add("bb");
list.add("cc");
}
@Override
public void run() {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
list.add("aa");
}
}
}