七、并发容器ConcurrentHashMap

一、简介

我们知道,HashMap是线程不安全的。而HashTable是线程安全的,但是JDK已经不建议使用HashTable,它已经被作为废除的实现。

在JDK并发包里面,ConcurrentHashMap支持并发操作,并包括HashMap的方法。

JDK文档:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/ConcurrentHashMap.html

二、示例

以下示例,我们使用CountDownLatch模拟了多线程并发操作。

而ConcurrentHashMap的putIfAbsent方法,将if判断和put的复合操作通过加锁,形成了一个原子操作支持并发。

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

public class ConcurrentHashMapDemo {

    public static ConcurrentHashMap<String, String> concurrentHashMap = new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    latch.await();
                    concurrentHashMap.putIfAbsent("threadName", Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
            }).start();
        }
        // 让子线程都等待
        Thread.sleep(10);
        // 并发执行
        latch.countDown();
        // 让子线程执行完毕
        Thread.sleep(1000);
        System.out.println(concurrentHashMap);
        System.out.println("finished");
    }
}

猜你喜欢

转载自www.cnblogs.com/lay2017/p/10165420.html