赞
踩
import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Created by byteyoung on 2020/8/24. */ public class readWriteLock{ public static void main(String[] args) { MycacheLock mycache = new MycacheLock(); for (int i = 0; i <10 ; i++) { final int tem = i ; new Thread(()->{ mycache.put(String.valueOf(tem),""+tem); },String.valueOf(tem)).start(); } //read for (int i = 0; i <10 ; i++) { final int tem = i ; new Thread(()->{ mycache.get(tem+""); },String.valueOf(tem)).start(); } } } class MycacheLock{ private volatile Map<String ,Object> map = new HashMap<>(); private ReadWriteLock readWriteLock = new ReentrantReadWriteLock (); //更加细粒度的控制 public void put(String key ,Object value){ //Lock.lock(); readWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"写入"+key); map.put(key,value); System.out.println(Thread.currentThread().getName()+"写入ok"+key); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.writeLock().unlock(); } } public void get(String key){ readWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName()+"读取"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取ok"+key); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.readLock().unlock(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。