我们都知道传统收藏(即。 列表 , 设置 , 队列 及其实现的类)和并发集合(即ConcurrentMap接口、ConcurrentHashMap类、CopyOnWriteArrayList类等)。在这两个系列中,几乎没有什么区别,比如:
null
- 课堂上出现的大多数课程 传统收藏(即 ArrayList , 链表 , 哈希图 等) 本质上是不同步的,因此没有线程安全性。但并发集合中的所有类本质上都是同步的。因此,在并发类中,我们不必关心线程安全。
- 而传统的藏品也有 有些课程(比如 矢量 , 堆栈 等) 它们在本质上是同步的,传统的收藏也有 SynchronizedSet,SynchronizedList,SynchronizedMap 方法,通过这些方法我们可以获得非同步对象的同步版本。但由于广泛的锁定机制,上述同步类在性能方面并不好。而并发集合类的性能相对高于传统集合类。
- 在传统的集合中,如果一个线程正在迭代一个集合对象,而另一个线程试图同时在该迭代对象中添加新元素,那么我们将得到 RuntimeException ConcurrentModificationException .而在上述情况下,如果我们使用并发集合类,则不会出现任何运行时异常。
- 如果我们在应用程序中不处理线程,那么传统的集合类是不错的选择。然而,由于并发/同步的集合,我们可以使用多个线程来处理集合对象。因此,如果我们在应用程序中处理多个线程,并发集合是最佳选择。
// Java program to illustrate Traditional // Collections Problem 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
// Java program to illustrate ConcurrentCollection uses import java.util.concurrent.CopyOnWriteArrayList; import java.util.*; class ConcurrentDemo extends Thread { static CopyOnWriteArrayList l = new CopyOnWriteArrayList(); 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); } } |
输出:
A B c
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END