任何集合类均可以经过使用同步包装器变成线程安全的:java
List<E> synchArrayList = Collections.synchronizedList(new ArrayList<E>()); Map<K,V> synchMap = Collections.synchronizedList(new HasMap<K,V>());
结果集合的方法使用锁加以保护,提供线程安全的访问。算法
若是在另外一个线程可能进行修改时要对集合进行迭代,任然须要使用封锁。安全
synchronized(synchHashMap) { Iterator<K> iter = synchHashMap.keySet().iterator(); while(iter.hasNext()) //遍历 }
若是使用for each 循环必须使用一样的代码,由于循环使用了迭代器。若是在迭代的过程当中另外一个线程修改集合,迭代器会失效,抛出ConcurrentModificationException异常,所以并发的修改能够被可靠的检测出来。数据结构
java.util.concurrent包提供了映像、有序集和队列的高效实现:ConcurrentHashMap、ConcurrentSkipListMap、ConcurrentLinkedQueue。这些集合经过复杂的算法,经过容许并发的访问数据结构的不一样部分来使竞争极小化。并发
这些集合返回弱一致性的迭代器。这意味着迭代器不必定能反映出他们被构造以后的全部的修改,可是,他们不会将同一个值返回两次,也不会抛出ConcurrentModificationException的异常。socket
package com.jie.concurrent; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; /** * * ConcurrentLinkedQueue是“线程安全”的队列,而LinkedList(ArrayList)是非线程安全的。 * * 下面是“多个线程同时操做而且遍历queue”的示例 * (01) 当queue是ConcurrentLinkedQueue对象时,程序能正常运行。 * (02) 当queue是LinkedList对象时,程序会产生ConcurrentModificationException异常。 * * \* Created with IntelliJ IDEA. * \* User: wugong.jie * \* Date: 2018/3/12 12:53 * \* To change this template use File | Settings | File Templates. * \* Description: * \ */ public class ConcurrentDemo { // queue是LinkedList对象时,程序会出错。 private static Queue<String> queue = new LinkedList<String>(); // private static Queue<String> queue = new ConcurrentLinkedQueue<String>(); public static void main(String[] args) { // 同时启动两个线程对queue进行操做! new MyThread("ta").start(); new MyThread("tb").start(); } private static void printAll() { String value; Iterator iter = queue.iterator(); while(iter.hasNext()) { value = (String)iter.next(); System.out.print(value+", "); } System.out.println(); } private static class MyThread extends Thread { MyThread(String name) { super(name); } @Override public void run() { int i = 0; while (i++ < 6) { // “线程名” + "-" + "序号" String val = Thread.currentThread().getName()+i; queue.add(val); // 经过“Iterator”遍历queue。 printAll(); } } } }
结果:多运行几回就出现下面的错误ide
Connected to the target VM, address: '127.0.0.1:1735', transport: 'socket' Exception in thread "tb" ta1, tb1, ta1, tb1, ta2, ta1, ta1, tb1, ta2, ta3, ta1, tb1, ta2, ta3, ta4, ta1, tb1, ta2, ta3, ta4, ta5, ta1, tb1, ta2, ta3, ta4, ta5, ta6, Disconnected from the target VM, address: '127.0.0.1:1735', transport: 'socket' java.util.ConcurrentModificationException at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966) at java.util.LinkedList$ListItr.next(LinkedList.java:888) at com.jie.concurrent.ConcurrentDemo.printAll(ConcurrentDemo.java:37) at com.jie.concurrent.ConcurrentDemo.access$100(ConcurrentDemo.java:22) at com.jie.concurrent.ConcurrentDemo$MyThread.run(ConcurrentDemo.java:54) Process finished with exit code 0