ReadWriteLock使用方法

  /**     * 多個線程同時讀一個資源類沒有任何問題,因此爲了知足併發量,讀取共享資源     * 應該同時進行。     * 可是,若是有一個線程想去寫共享資源來,就不該該再有其它線程能夠對該資源進行讀或者寫     * 小結:     * 讀—讀能共存     * 讀寫不能共存     * 寫寫不能共存     */    public static void main(String[] args) {        Mycache mycache=new Mycache();        for(int i=0;i<=5;i++){            final int t=i;         new Thread(()->{             mycache.put(Thread.currentThread().getName(),t+"");         },String.valueOf(i)).start();        }        for(int i=0;i<=5;i++){            new Thread(()->{                mycache.get(Thread.currentThread().getName());            },String.valueOf(i)).start();        }    }}class Mycache{    private volatile HashMap<String,Object> hashMap=new HashMap<>();    private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();    public void  put(String key, Object value){       readWriteLock.writeLock().lock();       try{           System.out.println(Thread.currentThread().getName()+"\t寫入數據"+key);           hashMap.put(key,value);           System.out.println(Thread.currentThread().getName()+"\t寫入完成");       }catch (Exception e){       }finally {           readWriteLock.writeLock().unlock();       }    }    public void get(String key){        readWriteLock.readLock().lock();        try{            System.out.println(Thread.currentThread().getName()+"\t讀取數據"+key);            hashMap.get(key);            System.out.println(Thread.currentThread().getName()+"\t讀取完成");        }catch (Exception e){        }finally {            readWriteLock.readLock().unlock();        }    }
相關文章
相關標籤/搜索