读写锁

  |   0 评论   |   1,402 浏览

    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.ReentrantReadWriteLock;
    
    /**
     * 读写锁
     * @author tonfay
     * 
     * 多线程同时读一个资源类没有问题
     * 只允许一个线程写
     *
     */
    public class ReadWriteLockDemo {
    	Map<String,Object> cache = new HashMap<String, Object>();
    	
    	public static void main(String[] args) {
    		Cache cache = new Cache();
    		
    		for(int i =1;i<=5;i++) {
    			final int tempi = i;
    			new Thread(new Runnable() {
    				@Override
    				public void run() {
    					cache.put(tempi+"", tempi+"");
    				}
    			}).start();
    		}
    		
    		
    		for(int i =1;i<=5;i++) {
    			final int tempi = i;
    			new Thread(new Runnable() {
    				@Override
    				public void run() {
    					cache.get(tempi+"");
    				}
    			}).start();
    		}
    	}
    }
    
    class Cache{
    	private volatile Map<String, Object> cache = new HashMap<String, Object>();
    	ReentrantReadWriteLock rrwlock = new ReentrantReadWriteLock();
    	
    	public void put(String key ,Object value) {
    		try {
    			rrwlock.writeLock().lock();
    			System.out.println(Thread.currentThread().getName() + "\t 开始put");
    			cache.put(key, value);
    			try {TimeUnit.MILLISECONDS.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}
    			System.out.println(Thread.currentThread().getName() + "\t put成功");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			rrwlock.writeLock().unlock();
    		}
    	}
    	
    	public void get(String key) {
    		try {
    			rrwlock.readLock().lock();
    			System.out.println(Thread.currentThread().getName() + "\t 开始get");
    			Object res = cache.get(key);
    			try {TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
    			System.out.println(Thread.currentThread().getName() + "\t get成功->"+ res);
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			rrwlock.readLock().unlock();
    		}
    	}
    }
    
    

    评论

    发表评论

    validate