JDK 1.5 之前同步容器包括:
  • Vector、Hashtable、Stack
  • Collections 工具类将普通容器,转变为同步容器,如:

public static <T> Collection<T> synchronizedCollection(Collection<T> c)public static <T> Set<T> synchronizedSet(Set<T> s)public static <T> List<T> synchronizedList(List<T> list)public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)


同步容器的实现原理就是在容器的操作方法上,加上了 synchronized 关键字。


JDK 1.5 开始,提供了并发容器,包括四大类:List、Set、Map、Queue

  • Set:CopyOnWriteArraySet、ConcurrentSkipListSet
  • Map:ConcurrentHashMap、ConcurrentSkipListMap
  • Queue:阻塞队列名称用 Blocking 标识,单端队列名称用 Queue 标识,双端队列名称用 Deque 标识

单端阻塞队列:ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue、LinkedTransferQueue、PriorityBlockingQueue、DelayQueue双端阻塞队列:LinkedBlockingDeque单端非阻塞队列:ConcurrentLinkedQueue双端非阻塞队列:ConcurrentLinkedDeque


下面示例中,当不把 list 转变为同步容器,并发 add,最后主线程打印 list,可能会报 java.util.ConcurrentModificationException 和 java.lang.ArrayIndexOutOfBoundsException,去掉注释就可以并发新增元素(当然最后打印的 list 不一定是元素的情况)

package constxiong.interview;
import java.util.ArrayList;import java.util.Collections;import java.util.List;
/** * 测试 同步容器与并发容器 * @author ConstXiong * @date 2019-12-26 20:56:32 */public class TestSynchronizedAndConcurrentCollection {  static List<Integer> list = new ArrayList<Integer>();
 public static void main(String[] args) throws InterruptedException {    testSynchronizedCollection();  }
 /**   * 测试同步容器   * @throws InterruptedException   */  private static void testSynchronizedCollection() throws InterruptedException {//    list = Collections.synchronizedList(list);    for (int i = 0; i < 300; i++) {      final int index = i;      new Thread(() -> {        list.add(index);      }).start();    }    System.out.println(list);  } }


并发容器的使用很简单,跟普通容器类似,如:

    /**   * 测试并发容器   */  private static void testConcurrentCollection() {    for (int i = 0; i < 300; i++) {      final int index = i;      new Thread(() -> {        map.put(index, index);      }).start();    }    System.out.println(map);  }





更多相关文章

  1. CopyOnWriteArrayList,一个面试中经常问到的冷门容器
  2. 聊一聊面试中常问的java阻塞队列
  3. 解读容器的 2020:寻找云原生的下一站
  4. 栈和队列就是这么简单
  5. 阻塞队列 BlockingQueue
  6. 队列(静态方式)
  7. 谷歌助力,快速实现 Java 应用容器化
  8. 队列(链式)
  9. 数据结构与算法(5)队列

随机推荐

  1. 将csv文件保存到现有文件,但在新工作表和
  2. MySQL+PHP配置 Windows系统IIS版(转)
  3. php分页代码的问题,显示了两个当前页码,求
  4. [轉]PHP官方网站,php官方论坛,中文函数手册
  5. 找不到go-pear。bat文件PHP 5.5 Windows
  6. 检索InnoDB组合密钥表的最后插入ID
  7. php 实现下载的方法
  8. 大文件从指定行开始读取
  9. 如何通过热门/上升的帖子订购
  10. mysql_query会自动执行,但不会在onClick时