美文网首页
Java并发 | ReentrantReadWriteLock类

Java并发 | ReentrantReadWriteLock类

作者: icebreakeros | 来源:发表于2019-08-08 20:49 被阅读0次

    ReentrantReadWriteLock类

    读写锁表示有两个锁,一个是读操作相关的锁,称为共享锁;另一个写操作相关的锁,称为排它锁
    多个线程可以同时进行读取操作,但同一时刻只允许一个线程进行写操作

    读写实例

    “读写”、“写读”、“写写”都是互斥的,而“读读”是异步的,非互斥的

    class Service {
    
        private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    
        public void read() {
            try {
                try {
                    lock.readLock().lock();
                    System.out.println("read lock:"
                            + Thread.currentThread().getName() + "-"
                            + System.currentTimeMillis());
                    Thread.sleep(10000);
                } finally {
                    lock.readLock().unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        public void write() {
            try {
                try {
                    lock.writeLock().lock();
                    System.out.println("write lock:"
                            + Thread.currentThread().getName() + "-"
                            + System.currentTimeMillis());
                    Thread.sleep(10000);
                } finally {
                    lock.writeLock().unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    class RService implements Runnable {
    
        private Service service;
    
        public RService(Service service) {
            this.service = service;
        }
    
        @Override
        public void run() {
            service.read();
        }
    }
    
    class WService implements Runnable {
    
        private Service service;
    
        public WService(Service service) {
            this.service = service;
        }
    
        @Override
        public void run() {
            service.write();
        }
    }
    
    public class Run {
    
        public static void main(String[] args) throws InterruptedException {
            Service service = new Service();
            Thread rThread = new Thread(new RService(service));
            rThread.start();
            Thread.sleep(1000);
    
            Thread wThread = new Thread(new WService(service));
            wThread.start();
        }
    }
    

    相关文章

      网友评论

          本文标题:Java并发 | ReentrantReadWriteLock类

          本文链接:https://www.haomeiwen.com/subject/scvfjctx.html