[英]Signal running thread1 to complete method1 after thread2 enters method2
I have 2 methods which need to function as below. 我有两种方法需要运行如下。
method1 {
1. run logic and insert into table1
}
method2 {
1. wait till other threads finish method1
2. block future threads from starting method1
3. update table1
}
The easiest solution would be to synchronize both method1 and method2. 最简单的解决方案是同步method1和method2。 Another point of consideration is that method1 can be invoked by multiple threads (>10) and is common operation, while method2 is called very very rarely.
另一个需要考虑的问题是,method1可以由多个线程调用(> 10)并且是常见的操作,而method2很少被调用。 So, synchronizing method1 will seriously hamper multiprocessing capability.
因此,同步方法1将严重妨碍多处理能力。
I explored the possibility of using ReadWriteLock, with a readLock in method1 and writeLock in method2. 我探讨了使用ReadWriteLock的可能性,方法2中的readLock和method2中的writeLock。 But that doesn't help me with #1 in method2, ie.
但这对方法2中的#1没有帮助,即。 after a writeLock is acquired in method2, I want running threads in method1 to complete before I proceed method2.
在method2中获取writeLock之后,我希望在继续执行method2之前在method1中运行线程。
This is a classic usage of ReadWriteLock
. 这是
ReadWriteLock
的经典用法。
See Java Concurrency with ReadWriteLock 请参阅使用ReadWriteLock的Java并发
The read lock may be held simultaneously by multiple reader threads, so long as there are no writers.
只要没有写入器,读锁定可以由多个读取器线程同时保持。 The write lock is exclusive .
写锁是独占的 。
So when you request a write lock in #1 of method2
it will wait until a time when all read locks have been released by anyone calling method1
before taking the lock and returning. 所以,当你在#1请求写入锁定
method2
将等到的时候,所有的读锁已被释放被任何人调用method1
取锁定并在返回之前。
Taking a write lock essentially performs both #1 and #2 of method2
. 以一个写锁基本上同时执行#1和#2
method2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.