zoukankan      html  css  js  c++  java
  • ReentrantReadWriteLock——写写互斥(二)

     "读写" 、"写读"、"写写"都是同步的、互斥的 

    1、Service.java

    package ReentrantReadWriteLock;
    
    import java.util.concurrent.locks.ReentrantReadWriteLock;
    
    public class Service {
    
        private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        
        //写写互斥
        public void write(){
            
            try{
                try{
                    lock.writeLock().lock();//写锁
                    System.out.println("获得写锁"+Thread.currentThread().getName()+" "+System.currentTimeMillis());
                    Thread.sleep(10000);
                }finally{
                    lock.writeLock().unlock();//解锁
                }
                
            }catch(Exception e){
                e.printStackTrace();
            }
            
        }
        
        
    }

    可以发现,lock.writeLock()的效果就是同一时间只允许一个线程执行lock()方法后面的代码

    2、ThreadA.java

    package ReentrantReadWriteLock;
    
    public class ThreadA extends Thread{
    
        private Service service ;
        
        public ThreadA(Service service){
            super();
            this.service = service;
        }
        
        @Override
        public void run(){
            service.write();
        }
        
        
    }

    3、ThreadB.java

    package ReentrantReadWriteLock;
    
    public class ThreadB extends Thread{
    
    private Service service ;
        
        public ThreadB(Service service){
            super();
            this.service = service;
        }
        
        @Override
        public void run(){
            service.write();
        }
        
        
    }

    4、Run.java

    package ReentrantReadWriteLock;
    
    public class Run {
    
        public static void main(String[] args) {
            
            Service service = new Service();
            ThreadA a = new ThreadA(service);
            a.setName("A");
            ThreadB b = new ThreadB(service);
            b.setName("B");
            a.start();
            b.start();
        }
    }

    可以自己更改ThreadA和ThreadB类中的run()方法里的read()、write()方法,实验"读写"、"写读"、"写写"

  • 相关阅读:
    elasticsearch中多个字段聚合及java实现
    elasticsearch中must和should组合查询
    Hash(哈希/散列)表中冲突处理及命中计算
    PHP代码审计理解(一)----Metinfo5.0变量覆盖
    SSL 3.0 POODLE攻击信息泄露漏洞_CVE-2014-3566
    菜鸡试飞----SRCの信息收集手册
    python3-邮件发送-不同格式
    windows下常用快捷指令记忆
    杂记
    偶然碰到的编码转换技巧--叮!
  • 原文地址:https://www.cnblogs.com/Donnnnnn/p/7237699.html
Copyright © 2011-2022 走看看