标签:style blog http io color ar java sp strong
给非同步的集合加锁:
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
方法
标签:style blog http io color ar java sp strong
原文地址:http://www.cnblogs.com/kongqis/p/4085869.html