JDK 中有哪些同步容器?并发容器?
16lz
2021-01-22
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); }
更多相关文章
- CopyOnWriteArrayList,一个面试中经常问到的冷门容器
- 聊一聊面试中常问的java阻塞队列
- 解读容器的 2020:寻找云原生的下一站
- 栈和队列就是这么简单
- 阻塞队列 BlockingQueue
- 队列(静态方式)
- 谷歌助力,快速实现 Java 应用容器化
- 队列(链式)
- 数据结构与算法(5)队列