10、JUC--ReadWriteLock 读写锁

读-写锁 ReadWriteLock

 ReadWriteLock 维护了一对相关的锁,一个用于只读操作,
  另一个用于写入操作。只要没有 writer,读取锁可以由
  多个 reader 线程同时保持。写入锁是独占的。。
 ReadWriteLock 读取操作通常不会改变共享资源,但执行
  写入操作时,必须独占方式来获取锁。对于读取操作占
  多数的数据结构。 ReadWriteLock 能提供比独占锁更高
  的并发性。而对于只读的数据结构,其中包含的不变性
  可以完全不需要考虑加锁操作。

 

ReadWriteLock读写锁

  写写/读写  需要互斥

  读读 不需要互斥

 

读写操作类

class readWriteLock{
    
    private int num = 0;
    
    //
    public void get(){
        System.out.println(Thread.currentThread().getName() +":" + num);
    }
    
    //
    public void set(int num){
        this.num = num;
    }
}

 

如果线程过多,此时读写同时操作

线程是不安全的

此时可以使用ReadWriterLock进行读写操作

更新上述的代码:

class readWriteLock{
    private int num = 0;
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    //
    public void get(){
        //读上锁
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() +"读:" + num);
        } finally {
            //读解锁
            lock.readLock().unlock();
        }
    }
    
    //
    public void set(int num){
        lock.writeLock().lock();
        try {
            this.num = num;
            System.out.println(Thread.currentThread().getName()+"写:" + this.num);
            
        } finally {
            lock.writeLock().unlock();
        }
    }
}

 

测试类中:

public static void main(String[] args) {
        readWriteLock rw = new readWriteLock();
        
        
        for(int i =0;i<=20;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    rw.set(new Random().nextInt());
                }
            }).start();
        }
        
        //
        for(int i =0;i<=20;i++){
                new Thread(new Runnable() {
                @Override
                 public void run() {
                     rw.get();
                }
            }).start();
        }
    }

 

测试结果:

Thread-4写:1380172948
Thread-10写:-1691293863
Thread-9写:-1957720735
Thread-3写:-18260563
Thread-5写:-1708073724
Thread-2写:-133847467
Thread-0写:-693555311
Thread-8写:855677820
Thread-1写:1224645831
Thread-6写:2059526025
Thread-7写:-1898498753
Thread-11写:1837102721
Thread-13写:-1025259351
Thread-14写:1964685852
Thread-15写:483772746
Thread-17写:-1091825320
Thread-18写:1416338338
Thread-16写:-2079049313
Thread-20写:1405392687
Thread-22读:1405392687
Thread-21读:1405392687
Thread-24读:1405392687
Thread-23读:1405392687
Thread-12写:1343396814
Thread-25读:1343396814
Thread-26读:1343396814
Thread-28读:1343396814
Thread-27读:1343396814
Thread-29读:1343396814
Thread-30读:1343396814
Thread-32读:1343396814
Thread-31读:1343396814
Thread-19写:-1883309938
Thread-33读:-1883309938
Thread-35读:-1883309938
Thread-34读:-1883309938
Thread-36读:-1883309938
Thread-39读:-1883309938
Thread-37读:-1883309938
Thread-38读:-1883309938
Thread-40读:-1883309938
Thread-41读:-1883309938

 

此时不会出现共享数据安全性的问题

 

posted @ 2019-05-02 14:28  MrChengs  阅读(212)  评论(0编辑  收藏  举报