zoukankan      html  css  js  c++  java
  • 用两个int值实现读写锁

     1 private int readcount = 0;
     2     private int writecount = 0;
     3     
     4     public void lockread() throws InterruptedException{
     5         while(writecount > 0){
     6             synchronized(this){
     7                 wait();
     8             }
     9         }
    10         readcount++;
    11         //进行读取操作
    12         System.out.println("读操作");
    13     }
    14     
    15     public void unlockread(){
    16         readcount--;
    17         synchronized(this){
    18             notifyAll();
    19         }
    20     }
    21     
    22     public void lockwrite() throws InterruptedException{
    23         while(writecount > 0){
    24             synchronized(this){
    25                 wait();
    26             }
    27         }
    28         //之所以在这里先++,是先占一个坑,避免读操作太多,从而产生写的饥饿等待
    29         writecount++;
    30         while(readcount > 0){
    31             synchronized(this){
    32                 wait();
    33             }
    34         }
    35         //进行写入操作
    36         System.out.println("写操作");
    37     }
    38     
    39     public void unlockwrite(){
    40         writecount--;
    41         synchronized(this){
    42             notifyAll();
    43         }
    44     }

      我们假设对写操作的请求比对读操作的请求更重要,就要提升写请求的优先级。

      此外,如果读操作发生的比较频繁,我们又没有提升写操作的优先级,那么就会产生“饥饿”现象。

      请求写操作的线程会一直阻塞,直到所有的读线程都从ReadWriteLock上解锁了。

     

  • 相关阅读:
    XML实例入门2
    XML入门
    XML实例入门1
    C语言复合梯形公式实现定积分
    一些界面库比较以及如何选择界面库
    网络阅读开篇
    vs2008 edit spin 十六进制实现
    jquery操作cookie
    Excel导入到DataTable
    SQL 查找某个字段的首字母
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/9848126.html
Copyright © 2011-2022 走看看