zoukankan      html  css  js  c++  java
  • ReadWriteLock

    ReadWriteLock也是一个接口,只有两个方法

    一个用来获取读锁,一个用来获取写锁。也就是说将文件的读写操作分开,分成2个锁来分配给线程,从而使得多个线程可以同时进行读操作。下面的ReentrantReadWriteLock实现了ReadWriteLock接口。

    public class Test {
        private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
        public static void main(String[] args)  {
            final Test test = new Test();
    
            new Thread(){
                public void run() {
                    test.get(Thread.currentThread());
                };
            }.start();
    
            new Thread(){
                public void run() {
                    test.get(Thread.currentThread());
                };
            }.start();
        }
        public void get(Thread thread) {
            rwl.readLock().lock();
            try {
                long start = System.currentTimeMillis();
    
                while(System.currentTimeMillis() - start <= 1) {
                    System.out.println(thread.getName()+"正在进行读操作");
                }
                System.out.println(thread.getName()+"读操作完毕");
            } finally {
                rwl.readLock().unlock();
            }
        }
    }

    说明thread-1和thread-0在同时进行读操作。

    这样就大大提升了读操作的效率。

     不过要注意的是,如果有一个线程已经占用了读锁,则此时其他线程如果要申请写锁,则申请写锁的线程会一直等待释放读锁。

    如果有一个线程已经占用了写锁,则此时其他线程如果申请写锁或者读锁,则申请的线程会一直等待释放写锁。

    来源:http://www.cnblogs.com/dolphin0520/

  • 相关阅读:
    使用C#调用系统API实现锁定计算机
    阶段性总结
    心情状态所困
    VMware虚拟机网络配置相关备忘
    数据库学习第一篇
    给window xp sp2设置共享文件夹
    转报竞赛实操试题
    数据库视频笔记
    Android开发从零开始,搭建交叉编译环境
    排故总结
  • 原文地址:https://www.cnblogs.com/gudulijia/p/6894682.html
Copyright © 2011-2022 走看看