LinkedList线程不安全处理

一、旧的线程安全的集合

任何集合类都可以通过使用同步包装器变成线程安全的:

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的异常。

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();
            }
        }
    }

}

结果:多运行几次就出现下面的错误

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

猜你喜欢

转载自my.oschina.net/wugong/blog/1633303