关于Map线程安全的几种实现方案

如果使Map线程安全,有四种方法:

1.使用synchronized关键字;

synchronized(anObject){

value = map.get(key);

}


2.使用JDK提供的锁,java.util.concurrent.locks.Lock;

lock.lock();

value = map.get(key);

lock.unlock():


3.使用JDK提供的读写锁java.util.concurrent.locks.ReadWriteLock.

rwlock.readLock().lock();

value= map.get(key);

rwlock.readLock().unlock();

这样两个读操作可以同时进行,理论上效率比lock要高;


4.使用JDK1.5提供的java.util.concurrent.ConcurrentHashMap,该类将Map的存储空间分为若干块,每块拥有自己的锁,减少了多个线程争夺同一个锁的情况.

value= map.get(key);//同步机制内置在get方法中


package com.imooc.concurrentmap;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Map线程安全的测试
 * 总结:
 */
public class MapTest {
	
	public static final int THREAD_COUNT = 1;
	public static final int MAP_SIZE = 1000;
	public static final int EXECUTION_MILLES = 1000;
	public static final int[] KEYS = new int[100];
	
	public static void main(String[] args) throws InterruptedException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {

		//创建线程
		long start = System.currentTimeMillis();
		Thread[] threads = new Thread[THREAD_COUNT];
		
		for (int i = 0; i < THREAD_COUNT; i++) {
			threads[i]  = new SynchronizedThread();//执行get次数和时间 : 37116922  (1004) ms
//			threads[i] = new LockThread();//执行get次数和时间 : 43899435  (1003) ms
//			threads[i] = new ConcurrentThread();//执行get次数和时间 : 90580822  (1004) ms
			threads[i].start();
		}
		
		//等待其他线程执行若干时间
		Thread.sleep(EXECUTION_MILLES);
		
		//统计get操作的次数
		long sum = 0;
		for (int i = 0; i < THREAD_COUNT; i++) {
			sum += threads[i].getClass().getDeclaredField("count").getLong(threads[i]);
		}
		
		long timeCost = System.currentTimeMillis() - start;
		System.out.println(sum + "  (" + timeCost + ") ms");
		
		System.exit(0);
		
	}
	
	/**
	 * 填充map
	 * @throws InterruptedException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	public static void fillMap(Map<Integer,Integer> map) {
		Random random = new Random();
		for (int i = 0; i < MAP_SIZE; i++) {
			map.put(random.nextInt(),random.nextInt());
		}
		
		
	}
	
	
}

class ConcurrentThread extends Thread {
	private static Map<Integer,Integer> map = new ConcurrentHashMap<Integer, Integer>();
	public long count = 0;
	static {
		MapTest.fillMap(map);
	}
	
	@Override
	public void run() {
		

		for(;;count++) {
			int index = (int) (count % MapTest.KEYS.length);
			map.get(MapTest.KEYS[index]);
		}
			
		
	}
	
}

/**
 * 同步代码块实现线程安全的MAP
 */
class SynchronizedThread extends Thread {
	private static Map<Integer,Integer> map = new HashMap<Integer, Integer>();
	public long count = 0;
	static {
		MapTest.fillMap(map);
	}
	
	
	@Override
	public void run() {
		
		for(;;count++) {
			int index = (int) (count% MapTest.KEYS.length);
			synchronized(SynchronizedThread.class) {
				map.get(MapTest.KEYS[index]);
			}
		}
		
	}
	
}

/**
 * Lock实现线程安全的map
 */
class LockThread extends Thread {
	
	private static Map<Integer,Integer> map = new HashMap<Integer,Integer>();
	
	private static Lock lock = new ReentrantLock();
	
	public long count = 0;
	
	static {
		MapTest.fillMap(map);
	}
	
	@Override
	public void run() {
		
		for(;;count++) {
			
			int index = (int) (count % MapTest.KEYS.length);
			lock.lock();
			map.get(MapTest.KEYS[index]);
			lock.unlock();
		}
		
	}
	
	
}




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值