手写缓存(读写锁)

读读共享,写写互斥,读写互斥
写锁是独占锁,读锁是共享锁

package Juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

/**
 * 读写锁实现手写缓存
 * 
 */
public class MyCache {
	
	private volatile Map<String ,Object> map= new HashMap<>();
	
	private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
	
	public void put(String key,Object value){
		rwLock.writeLock().lock();
		try {
			System.out.println(Thread.currentThread().getName()+"\t 正在写入"+ key);
			try{TimeUnit.MILLISECONDS.sleep(300);}catch (Exception e){e.printStackTrace();}
			map.put(key, value);
			System.out.println(Thread.currentThread().getName()+"\t 写入完成!");
		}catch(Exception e){
			e.printStackTrace();
		}
		finally {
			rwLock.writeLock().unlock();
		}
		
		
	}
	public void get(String key){
		rwLock.readLock().lock();
		try {
			System.out.println(Thread.currentThread().getName()+"\t 正在读入"+ key);
			try{TimeUnit.MILLISECONDS.sleep(300);}catch (Exception e){e.printStackTrace();}
			Object result=	map.get(key);
			System.out.println(Thread.currentThread().getName()+"\t 读入完成"+result);
		}catch(Exception e){
			e.printStackTrace();
		}
		finally {
			rwLock.readLock().unlock();
		}
		}
	public void cleanMap(){
		map.clear();
	}
	
	public static void main(String[] args) {
		MyCache myCache = new MyCache();
		
		for (int i = 0; i < 10; i++) {
			final int tempInt = i;
			new Thread(() -> {
				myCache.put(tempInt+"",tempInt+"");
			},String.valueOf(i)).start();
		}
		
		
		for (int i = 0; i < 10; i++) {
			final int tempInt = i;
			new Thread(() -> {
				myCache.get(tempInt+"");
			},String.valueOf(i)).start();
		}
		
	}

}

你可能感兴趣的:(JUC多线程及高并发)