<分区>
如果我创建这样一个列表:
List<MyObj> myobjs = Collections.synchronizedList(new ArrayList<MyObj>());
相关文档声称此返回列表需要同步才能遍历元素。然而,我可以同步一个常规列表并用同步块(synchronized block)保护它。那么,为什么我需要一个“synchronizedList”?
Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.
It is imperative that the user manually synchronize on the returned list when iterating over it:
List list = Collections.synchronizedList(new ArrayList());
...
synchronized (list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
Failure to follow this advice may result in non-deterministic behavior. The returned list will be serializable if the specified list is serializable.
Parameters: list the list to be "wrapped" in a synchronized list. Returns: a synchronized view of the specified list.