List<String> list = new ArrayList<String>(); list.add("a"); ... list.add("z"); synchronized(list) { Iterator<String> i = list.iterator(); while(i.hasNext()) { ... } }
和
List<String> list = new ArrayList<String>(); list.add("a"); ... list.add("z"); List<String> synchronizedList = Collections.synchronizedList(list); synchronized(synchronizedList) { Iterator<String> i = synchronizedList.iterator(); while(i.hasNext()) { ... } }
具体来说,当同步列表提供对列表的线程安全访问时,我不清楚为什么在第二个实例中需要同步.