fingerPower 2013-04-09 14:56
浏览 770
已采纳

ConcurrenthashMap如何实现并发操作

请教一个问题,

首先在ConcurrenthashMap中预置10万条测试数据

1,我如何使用一个线程对ConcurrenthashMap作操作,先get(key),接着remove(key),直到所有数据remove,记录一下所有时间

2,我如何使用多个线程(3个线程)对ConcurrenthashMap作上面同样的操作,我需要得到两种处理方式所使用的时间

希望能给我简单的demo,谢谢了,小弟线上等待。。。

  • 写回答

2条回答 默认 最新

  • cectsky 2013-04-09 17:56
    关注

    public class ConcurrentHashMapTest {

    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMap<Integer,String> map = new ConcurrentHashMap<Integer,String>();
        for(int i=0;i<10*10000;i++){
            map.put(i, String.valueOf(i));
        }
    
        System.out.println("prepare test data of 10w");
    
        new Consumer(map,1).start();
    
        Thread.sleep(1000);
        ConcurrentHashMap<Integer,String> map1 = new ConcurrentHashMap<Integer,String>();
        for(int i=0;i<10*10000;i++){
            map1.put(i, String.valueOf(i));
        }
        for(int i=0;i<3;i++){
            new Consumer(map1,2).start(); 
        }
    
    }
    

    }
    class Consumer extends Thread{
    ConcurrentHashMap map;
    int which;
    public Consumer(ConcurrentHashMap map,int which){
    this.map = map;
    this.which = which;
    }
    @Override
    public void run() {
    long start = System.currentTimeMillis();
    for(Integer key : map.keySet()){
    map.get(key);
    map.remove(key);
    }
    System.out.println("The "+which+" cost "+(System.currentTimeMillis()-start)+"ms");
    }

    }

    执行三次,发现单线程性能cost比较稳定,3个线程会有波动,按照最长时间的线程来看,有可能性能还不如single的,可见concurrenthashmap对于同步处理还是有一定的开销的
    prepare test data of 10w for 1
    The 1 cost 18ms
    prepare test data of 10w for 2
    The 2 cost 13ms
    The 2 cost 14ms
    The 2 cost 12ms

    prepare test data of 10w for 1
    The 1 cost 18ms
    prepare test data of 10w for 2
    The 2 cost 20ms
    The 2 cost 19ms
    The 2 cost 16ms

    prepare test data of 10w for 1
    The 1 cost 18ms
    prepare test data of 10w for 2
    The 2 cost 14ms
    The 2 cost 13ms
    The 2 cost 16ms

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊