同步容器类
概念
Collections类里面有方法可以将普通的容器加上一把锁
例子如下
Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
并发容器类
ConcurrentMap
传统方式的缺点运用锁如下图
ConcurrentMap是对每一个段进行操作提高读写效率:如下图
案例代码
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class UseConcurrentMap {
public static void main(String[] args) {
ConcurrentHashMap<String, Object> chm = new ConcurrentHashMap<String, Object>();
chm.put("k1", "v1");
chm.put("k2", "v2");
chm.put("k3", "v3");
chm.putIfAbsent("k3", "vvvv");//如果key相同的 就不会继续放入
//System.out.println(chm.get("k2"));
//System.out.println(chm.size());
for(Map.Entry<String, Object> me : chm.entrySet()){
System.out.println("key:" + me.getKey() + ",value:" + me.getValue());
}
}
}
Copy-On-Write容器(读多写少应用)
如果写的操作太多还是建议用现成加锁来完成
复制数据,对数据进行操作 如下图
实现类中之一CopyOnWriteArray方法底层方法是加锁的 这种锁的形式叫:重入锁
代码例子
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
public class UseCopyOnWrite {
public static void main(String[] args) {
CopyOnWriteArrayList<String> cwal = new CopyOnWriteArrayList<String>();
CopyOnWriteArraySet<String> cwas = new CopyOnWriteArraySet<String>();
}
}