List safeList = Collections.synchronizedList(new ArrayList()); // adds some elements to the list Iterator iterator = safeList.iterator(); while (iterator.hasNext()) { String next = iterator.next(); System.out.println(next);}
复制代码
事实上我们应该这样来写:
如果在另一个线程可能进行修改时,要对集合进行迭代,仍然需要使用锁,如下:
List safeList = Collections.synchronizedList(new ArrayList()); new Thread(new Runnable() { @Override public void run() { synchronized (safeList) { for (int i = 0; i < 110; i++) { safeList.add(i + ""); } } } }).start(); new Thread(new Runnable() { @Override public void run() { Iterator iterator = safeList.iterator(); synchronized (safeList) { while (iterator.hasNext()) { String next = iterator.next(); System.out.println(next); } } } }).start();