给非同步的集合加锁:

class MyCollections{//创建工具类,提供对外访问方法

    public static list synList(List list){
        return new MyList(list);
    }
    
    
    private Class MyList implements List{
    
        private List list;
        private static final Object lock = new Object();
        
        MyList(List list){
            this.list = list;
        }
        
        public boolean add(Object obj){
            synchronized(lock)
            {
            return list.add(obj);
            }
        }
        public boolean remove(Object obj){
            synchronized(lock)
            {
            return list.remove(obj);
            }
        }
        
    }

}

 

List list = new ArrayList(); //非同步的

 

list = MyCollections.synList(list);//返回一个同步的list

 

此过程就是 Coolections 工具类中的 synchronizedList 方法


 

posted on 2014-11-09 20:54  小丑的自嘲  阅读(1044)  评论(0编辑  收藏  举报