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


原文链接
 


 

猜你喜欢

转载自www.cnblogs.com/ConstXiong/p/12118001.html