ConcurrentHashMap 测试

package com.huang.test.concurrent;

import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ConcurrentHashMap"添加移除线程安全
 * 1.获取size用mappingCount方法(返回long,不是准确的)。
 * 2.遍历时可同时修改。
 */
public class ConcurrentHashMapTest
{
    int len = 100;
    private ConcurrentHashMap map = new ConcurrentHashMap<>();
    public static void main(String[] args) {
        ConcurrentHashMapTest cht = new ConcurrentHashMapTest();
        cht.test();
    }

    private void test() {
        ExecutorService exec = Executors.newFixedThreadPool(len);
        ArrayList> tasks = new ArrayList<>();
        for(int i = 0;i < len;i++)
        {
            tasks.add(new MyCallable(map, i));
        }
        try {
            exec.invokeAll(tasks);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        printMap(map);
        exec.shutdown();
    }

    private void printMap(ConcurrentHashMap map)
    {
        Set> ks = map.entrySet();
        TreeMap treeMap = new TreeMap<>();
        for(Map.Entry item:ks)
        {
            int key = item.getKey();
            String value = item.getValue();
            treeMap.put(key, value);
        }

        Set> es = treeMap.entrySet();
        System.out.println("size:" + map.mappingCount());
        for(Map.Entry item:es)
        {
            System.out.println(item.getKey() + " " + item.getValue());
        }
    }

    class MyCallable implements Callable{
        private int sec;
        private ConcurrentHashMap map;

        public MyCallable(ConcurrentHashMap map, int sec)
        {
            this.map = map;
            this.sec = sec;
        }

        @Override
        public Void call() {
            map.put(sec, "value" + sec);
            return null;
        }
    }
}

 

你可能感兴趣的:(java,并发编程)