java方法同步和读/写互斥 [英] java method synchronization and read/write mutual exclusion

查看:251
本文介绍了java方法同步和读/写互斥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类中有两个方法 read() write()

I have two methods read() and write() as below in a class.

class Store
{

  public void write()
  {
    // write to store;
  }

  public string  read()
  {
    // read from store;
  }
}

1) / code> object是一个单例。

1) The Store object is a singleton.

2)我有一个 Writer 商店和几个 Reader 类将同时从商店读取。

2) I have a Writer class which will write to the store and several Reader classes which will read from the store at the same time.

我的要求是,当作家正在写给商店,所有的读者都应该等待。即当控制在 write()中时,应该阻止对 read()的所有调用。我如何实现这一点?我在 write()方法中尝试了同步(Store.class),但似乎不工作在这种情况下,最好的选择是使用读写器锁:

My requirement is that when the writer is writing to the store, all the readers should wait. i.e., when control is in write(), all the calls to read() should be blocked. How do I achieve this? I have tried synchronize(Store.class) in the write() method, but doesn't seem like work for me.

推荐答案

/docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html\">ReadWriteLock

The best option in this case is to use a reader-writer lock: ReadWriteLock. It allows a single writer, but multiple concurrent readers, so it's the most efficient mechanism for this type of scenario.

一些示例代码:

class Store
{
    private ReadWriteLock rwlock = new ReentrantReadWriteLock();

    public void write()
    {
       rwlock.writeLock().lock();
       try {
          write to store;
       } finally {
          rwlock.writeLock().unlock();
       }
    }

    public String read()
    {
       rwlock.readLock().lock();
       try {
          read from store;
       } finally {
          rwlock.readLock().unlock();
       }
    }
}

这篇关于java方法同步和读/写互斥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆