Donnie

不积跬步无以至千里

读写锁ReadWriteLock

顾名思义分为读锁和写锁,
多个线程访问读锁不互斥,只要有写锁参与就互斥,如一个线程获得了读锁,另一个写锁就必须等待互斥,反之也是互斥
读读不互斥,读写互斥,写写互斥

    public class ReadWriteLockDemo {
    
        private static ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    
        private static LinkedList<String> list = new LinkedList<>();
    
        public static void setValue(){
    
            rwLock.writeLock().lock();
    
            System.out.println("hi write lock");
    
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            list.add("demo");
    
            rwLock.writeLock().unlock();
    
        }
    
        //未加读锁会出现脏读,或者还未写入值,就出现异常
        public static String getNoReadLockValue(){
            String s = list.get(0);
            return s;
        }
    
        //加了读锁,如果写锁先拿到锁,会等待写锁完成,才能或得到值
        public static String getReadLock(){
    
            rwLock.readLock().lock();
            String s = list.get(0);
            rwLock.readLock().unlock();
            return s;
        }
    
        public static void main(String[] args) {
            
            Thread t1 = new Thread(()->{
    
                setValue();
    
            });
    
            t1.start();
    
            Thread t2 = new Thread(()->{
    
                System.out.println(getReadLock());
    //            System.out.println(getNoReadLockValue());
    
            });
    
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            t2.start();
    
        }
    }
赞赏支持