简体   繁体   中英

Synchronization of Threads in Java

You have a storage object O.

Assume you have n reader methods and one writer method in a thread. If the writer method is called by a thread, none of the reader methods should be able to access O, but if a reader method accesses O, any other reader may access O but not the writer. Can I somehow implement this behaviour using "synchronized" statements in Java? If not: How else could I achieve this?

Thank you in advance.

You could use a ReadWriteLock . You allocate it somewhere where the reader and writer threads can access it. Maybe pass it into their constructors.

ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

Readers would do:

Lock lock = readWriteLock.readLock();
lock.lock();
try {
  // do read operations here...
} finally {
  lock.unlock();
}

Writers would do:

Lock lock = readWriteLock.writeLock();
lock.lock();
try {
  // do write operations here...
} finally {
  lock.unlock();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM