用两个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上解锁了。

 

原文地址:https://www.cnblogs.com/mengchunchen/p/9848126.html