码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-04-29 16:16:26      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:let   blog   str   sync   util   控制   线程安全   lis   更改   

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

常用的容器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;

 

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

标签:let   blog   str   sync   util   控制   线程安全   lis   更改   

原文地址:http://www.cnblogs.com/rimonzheng/p/6785252.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!