java 并发集合的必要性

java 并发集合的必要性

我们已经知道,集合就是对象的集合,我们使用一些预定义的方法来处理这些对象。但是,当我们在多线程中使用集合概念时,会出现一些问题。在多线程应用程序中使用集合时出现的问题。

  • 大多数集合类对象(如ArrayList、LinkedList、HashMap等)都是非同步的,即多个线程可以同时对一个对象进行操作。因此,对象不是线程安全的。
  • 极少数的类对象(如Vector、Stack、HashTable)是同步的,即在同一时间只有一个线程可以对一个对象进行操作。但这里的问题是性能很低,因为在一个时间内只有一个线程执行一个对象,其他线程必须等待。
  • 主要的问题是,当一个线程在迭代一个集合对象时,如果另一个线程不能修改该对象的内容。如果另一个线程试图修改对象的内容,那么我们会得到RuntimeException,即ConcurrentModificationException。
  • 由于上述原因,集合类并不适合,或者说我们可以说是多线程应用的好选择。

为了克服上述问题,SUN microSystem在JDK 1.5版本中引入了一个新特性,即并发集合。

// Java program to illustrate Concurrent
// Collection need
import java.util.*;
class ConcurrentDemo extends Thread {
    static ArrayList l = new ArrayList();
    public void run()
    {
        try {
            Thread.sleep(2000);
        }
        catch (InterruptedException e) {
            System.out.println("Child Thread" + 
                      " going to add element");
        }
  
        // Child thread trying to add new
        // element in the Collection object
        l.add("D");
    }
  
    public static void main(String[] args) 
                   throws InterruptedException
    {
        l.add("A");
        l.add("B");
        l.add("c");
  
        // We create a child thread that is 
        // going to modify ArrayList l.
        ConcurrentDemo t = new ConcurrentDemo();
        t.start();
  
        // Now we iterate through the ArrayList
        // and get exception.
        Iterator itr = l.iterator();
        while (itr.hasNext()) {
            String s = (String)itr.next();
            System.out.println(s);
            Thread.sleep(6000);
        }
        System.out.println(l);
    }
}

输出:

Exception in thread “main” java.util.ConcurrentModificationException

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程