Java基础(十二)----concurrentHashMap与线程池

来源:互联网 发布:专业 知乎 编辑:程序博客网 时间:2024/06/06 08:41

一、 concurentHashMap
1、 hashmap、hashtable、concurrentHashMap
hashmap: 非线程安全的
hashtable: 线程安全的,通过锁定整个map来保证线程安全,效率低下
concurrentHashMap: 线程安全的,一个concurrentHashMap中有多个锁,每次操作时,只能保证单次操作的原子性,如: 单次put或单次get,如果put和get同时需要保证原子性,则concurrentHashMap无法保证,必须用其他方法(synchronized)

package test;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;public class Test {    public static void main(String[] args) throws InterruptedException {        for (int i = 0; i < 8; i++) {            System.out.println(test());        }    }    private static int test() throws InterruptedException {        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();        ExecutorService pool = Executors.newCachedThreadPool();        for (int i = 0; i < 8; i++) {            pool.execute(new MyTask(map));        }        // 线程池关闭操作        pool.shutdown();        pool.awaitTermination(1, TimeUnit.DAYS);        return map.get(MyTask.KEY);    }}class MyTask implements Runnable {    static Object lock = new Object();    static final String KEY = "key";    ConcurrentHashMap<String, Integer> map;    public MyTask(ConcurrentHashMap<String, Integer> map) {        this.map = map;    }    @Override    public void run() {        for (int i = 0; i < 100; i++) {            synchronized (lock) {                addup();            }        }    }    private void addup() {        if (!map.containsKey(KEY))             map.put(KEY, 1);        else             map.put(KEY, map.get(KEY) + 1);    }}

concurrentHashMap源码解析
源码
浅析HashMap与ConcurrentHashMap的线程安全性

阅读全文
0 0