容器的同步控制与只读设置

一.同步控制: 用于多线程并发访问容器资源的线程安全

常用的容器ArrayList HashMap HashSet都是线程不安全的
Collections 中提供了SynchronizedXxx() 方法用于包装容器为同步的 

List<String> list = new ArrayList<String>();
        
List<String> list2 = Collections.synchronizedList(list); // list为线程安全

二.容器只读控制

  容器只读设置 util包下的Collections提供了三种办法:
   (1) emptyXxx()
   (2) singletonXxx()
   (3) unmodifiableXxx()

Map<String , String> map = new HashMap<String ,String>();
        map.put("num1", "value1");
        map.put("num2", "value2");
        map = Collections.unmodifiableMap(map); // 不能再更改容器内容 ,只允许读取
        map.put("num3", "value3");   // 此行会报错
        
        List<String> list3 = Collections.singletonList(new String());
        list3.add("rimon1");
        list3.add("rimon2");  // 只能添加一个元素
    
        
    }
    public static Set<String> emp(Set<String> set){
        if(set == null){
            return Collections.EMPTY_SET;  //防止出现 nullpointerException
        }
        return set;

 

posted @ 2017-04-29 14:58  rimonzheng  阅读(319)  评论(0编辑  收藏  举报