解决并发情况下的容器线程安全问题的。给多线程环境准备一个线程安全的容器对象。
线程安全的容器对象: Vector, Hashtable。线程安全容器对象,都是使用 synchronized
方法实现的。
concurrent 包中的同步容器,大多数是使用系统底层技术实现的线程安全。类似 native。
Java8 中使用 CAS。
1. Map/Set
1.1 ConcurrentHashMap/ConcurrentHashSet
底层哈希实现的同步 Map(Set)。效率高,线程安全。使用系统底层技术实现线程安全。
量级较 synchronized 低。key 和 value 不能为 null。
1.2 ConcurrentSkipListMap/ConcurrentSkipListSet
底层跳表(SkipList)实现的同步 Map(Set)。有序,效率比 ConcurrentHashMap稍低。
跳表专题
public static void main(String[] args) {
//Hashtable底层采用同步方式实现
final Map<String, String> map = new Hashtable<>();
//底层哈希实现的同步
//final Map<String, String> map = new ConcurrentHashMap<>();
//底层使用跳表实现
// final Map<String, String> map = new ConcurrentSkipListMap<>();
final Random r = new Random();
Thread[] array = new Thread[100];
final CountDownLatch latch = new CountDownLatch(array.length);
long begin = System.currentTimeMillis();
for(int i = 0; i < array.length; i++){
array[i] = new Thread(new Runnable() {
@Override
public void run() {
for(int j = 0; j < 100000; j++){
map.put("key"+r.nextInt(1000000), "value"+r.nextInt(100000));
}
latch.countDown();
}
});
}
for(Thread t : array){
t.start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("执行时间为 : " + (end-begin) + "毫秒!");
}
2. List
2.1 CopyOnWriteArrayList
写时复制集合。 写入效率低, 读取效率高。 每次写入数据, 都会创建一个新的底层数组。
3. Queue
3.1 ConcurrentLinkedQueue
基础链表同步队列。

public static void main(String[] args) {
Queue<String> queue = new ConcurrentLinkedQueue<>();
for(int i = 0; i < 10; i++){
queue.offer("value" + i);
}
System.out.println(queue);
System.out.println(queue.size());
// peek() -> 查看queue中的首数据
System.out.println(queue.peek());
System.out.println(queue.size());//10
// poll() -> 获取queue中的首数据
System.out.println(queue.poll());
System.out.println(queue.size());//9
}
3.2 LinkedBlockingQueue
阻塞队列,队列容量不足自动阻塞,队列容量为 0 自动阻塞。
put & take - 自动阻塞。

3.3 ArrayBlockingQueue
底层数组实现的有界队列。自动阻塞。根据调用 API(add/put/offer)不同,有不同特
性。
当容量不足的时候,有阻塞能力。
add 方法在容量不足的时候,抛出异常。
put 方法在容量不足的时候,阻塞等待。
offer 方法,
单参数 offer 方法,不阻塞。容量不足的时候,返回 false。当前新增数据操作放弃。
三参数 offer 方法(offer(value,times,timeunit)) ,容量不足的时候,阻塞 times 时长(单
位为 timeunit) ,如果在阻塞时长内,有容量空闲,新增数据返回 true。如果阻塞时长范围
内,无容量空闲,放弃新增数据,返回 false。


3.4 DelayQueue
延时队列。根据比较机制,实现自定义处理顺序的队列。常用于定时任务。
如:定时关机。
3.5 LinkedTransferQueue
转移队列,使用 transfer 方法,实现数据的即时处理。没有消费者,就阻塞。
3.6 SynchronusQueue
同步队列,是一个容量为 0 的队列。是一个特殊的 TransferQueue。
必须现有消费线程等待,才能使用的队列。
add 方法,无阻塞。若没有消费线程阻塞等待数据,则抛出异常。
put 方法,有阻塞。若没有消费线程阻塞等待数据,则阻塞。
本文深入解析了Java中多种并发容器的工作原理及应用场景,包括线程安全的Vector和Hashtable,高效的ConcurrentHashMap与ConcurrentHashSet,以及适用于不同需求的Queue实现如ConcurrentLinkedQueue和ArrayBlockingQueue等。
482

被折叠的 条评论
为什么被折叠?



