zoukankan      html  css  js  c++  java
  • JDK 中有哪些同步容器?并发容器?

    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 关键字。


    List:CopyOnWriteArrayList

    • Set:CopyOnWriteArraySet、ConcurrentSkipListSet
    • Map:ConcurrentHashMap、ConcurrentSkipListMap
    • Queue:阻塞队列名称用 Blocking 标识,单端队列名称用 Queue 标识,双端队列名称用 Deque 标识
    1. 单端阻塞队列:ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue、LinkedTransferQueue、PriorityBlockingQueue、DelayQueue
    2. 双端阻塞队列:LinkedBlockingDeque
    3. 单端非阻塞队列:ConcurrentLinkedQueue
    4. 双端非阻塞队列: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);
        }


    原文链接
     


     

  • 相关阅读:
    1539. Kth Missing Positive Number (E)
    0082. Remove Duplicates from Sorted List II (M)
    0526. Beautiful Arrangement (M)
    解决mac电脑耳机/外放突然无声音
    利用蒙特卡洛方法实现21点问题的最优解(内含python源码)
    浅析机器视觉在医疗影像处理中的应用
    基于最近邻法手写数字识别(内附python源码)
    最新版 | 2020李沐《动手学深度学习》中文版pdf重磅开源!
    干货收藏!639页《深度学习:Deep Learning》图文并茂课程PPT
    22课时、19大主题,CS 231n进阶版课程视频上线!
  • 原文地址:https://www.cnblogs.com/ConstXiong/p/12118001.html
Copyright © 2011-2022 走看看