简体   繁体   English

Java中的线程同步

[英]Synchronization of Threads in Java

You have a storage object O. 您有一个存储对象O。

Assume you have n reader methods and one writer method in a thread. 假设您在一个线程中有n个读者方法和一个作家方法。 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. 如果通过线程调用writer方法,则所有读取器方法都不能访问O,但是如果读取器方法访问O,则任何其他读取器都可以访问O,但不能访问writer。 Can I somehow implement this behaviour using "synchronized" statements in Java? 我可以使用Java中的“同步”语句以某种方式实现此行为吗? If not: How else could I achieve this? 如果没有:我还能如何实现?

Thank you in advance. 先感谢您。

You could use a ReadWriteLock . 您可以使用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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