问题描述
请教一个问题,首先在ConcurrenthashMap中预置10万条测试数据1,我如何使用一个线程对ConcurrenthashMap作操作,先get(key),接着remove(key),直到所有数据remove,记录一下所有时间2,我如何使用多个线程(3个线程)对ConcurrenthashMap作上面同样的操作,我需要得到两种处理方式所使用的时间希望能给我简单的demo,谢谢了,小弟线上等待。。。 问题补充:求帮忙!!!
解决方案
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<Integer,String> map;int which;public Consumer(ConcurrentHashMap<Integer,String> map,int which){this.map = map;this.which = which;}@Overridepublic 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 1The 1 cost 18msprepare test data of 10w for 2The 2 cost 13msThe 2 cost 14msThe 2 cost 12msprepare test data of 10w for 1The 1 cost 18msprepare test data of 10w for 2The 2 cost 20msThe 2 cost 19msThe 2 cost 16msprepare test data of 10w for 1The 1 cost 18msprepare test data of 10w for 2The 2 cost 14msThe 2 cost 13msThe 2 cost 16ms
解决方案二:
你这测试的肯定有问题,ConcurrenthashMap使用的分离锁,多线程不可能比单线程时间还长。