Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的同步读写器_Java_Multithreading - Fatal编程技术网

java中的同步读写器

java中的同步读写器,java,multithreading,Java,Multithreading,我想实现自己的readWriteLock类,而不使用API提供的readWriteLock 我有这样的情况: public void read(){ if(!write){ read = true; //any thread can enter here and read; .... read = false; } } public syncrhonized void write(){ if(!read){ write

我想实现自己的
readWriteLock
类,而不使用API提供的
readWriteLock

我有这样的情况:

public void read(){
    if(!write){
    read = true;
   //any thread can enter here and read;
    ....
    read = false;
    }
}

 public syncrhonized void write(){
    if(!read){
         write = true;
         //only one thread at time can write.
         ....
         write = false;
   }
}
此代码可能会出现很多不好的情况,例如:

  • 如果一个线程进入
    if(!read){…}
    内部,它会立即变为true,因此无法写入
  • 如果线程进入
    if(!write){…}
    内部,这将立即变为真,因此它们无法读取
我设法使用了
atomicBoolean
,但是对于同时想要读取的所有线程来说,这是一个
mutex-exclusion
,这并不能解决歧义

有人能给我解释一下吗


提前谢谢。

你想做的不是一个好主意。正如你已经提到的那样,已经有了一个现有的机制。为什么要重新发明轮子

如果您确实需要自己的实现,那么要正确地实现它,需要更多的同步块。您需要同步获取和释放读锁,您不能只同步对写方法的访问

我没有检查过的示例,但看起来不错。Jakob Jenkov()


典型的死锁情况。为了防止出现这种情况,请查看信号量。java.util.concurrent.locks.ReentrantReadWriteLock有什么问题
public class ReadWriteLock{

  private int readers       = 0;
  private int writers       = 0;
  private int writeRequests = 0;

  public synchronized void lockRead() throws InterruptedException{
    while(writers > 0 || writeRequests > 0){
      wait();
    }
    readers++;
  }

  public synchronized void unlockRead(){
    readers--;
    notifyAll();
  }

  public synchronized void lockWrite() throws InterruptedException{
    writeRequests++;

    while(readers > 0 || writers > 0){
      wait();
    }
    writeRequests--;
    writers++;
  }

  public synchronized void unlockWrite() throws InterruptedException{
    writers--;
    notifyAll();
  }
}