zoukankan      html  css  js  c++  java
  • ReentrantReadWriteLock——读读共享(一)

    多个线程可以同时读,读读是异步的、非互斥的

    1、Service.java(封装的方法,供线程A和B访问)

    package ReentrantReadWriteLock;
    
    import java.util.concurrent.locks.ReentrantReadWriteLock;
    
    public class Service {
    
        private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        
        public void read(){
            try{
                try{
                    lock.readLock().lock();//读锁
                    System.out.println("获得读锁"+Thread.currentThread().getName()+" "+System.currentTimeMillis());
                    Thread.sleep(10000);//验证A和B是否同时读进来
                }finally{
                    lock.readLock().unlock();//解锁
                }
                
            }catch(Exception e){
                e.printStackTrace();
            }
            
        }
        
    }

    2、ThreadA.java(线程A)

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

    3、ThreadB.java(线程B)

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

    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();
        }
    }
  • 相关阅读:
    CASE WHEN用法
    BOS消息对话框
    BOS自定义等待窗口
    自定义F7
    BOS接口开发
    BOS开发-增删改查
    金蝶BOS工作流
    金蝶KDTable常用代码
    BOS开发常用代码
    Jenkins2 入门到精通(学习资料)
  • 原文地址:https://www.cnblogs.com/Donnnnnn/p/7235343.html
Copyright © 2011-2022 走看看