转换等待& notifyAll代码使用Java 1.5 Lock对象 [英] Convert wait & notifyAll code to use Java 1.5 Lock object
问题描述
我们使用的代码使用代码段周围的同步块,有很多wait和notifyAll()调用。我们试图将这些转换为使用Java 5 Lock.lock()和Lock.unlock()方法。如何迁移此代码以删除所有等待和notifyAll调用。我不知道相当于这些使用新的锁定功能。
We use code that uses syncronized blocks around segments of code with a lot of wait and notifyAll() calls. We are trying to convert these to use Java 5 Lock.lock() and Lock.unlock() methods. How do I migrate this code to remove all the wait and notifyAll calls. I do not know the equivalent to these using the new Locking features.
任何链接的例子将不胜感激。
Any links with examples would be appreciated.
感谢进行
方程式,下面的代码需要转换为使用Lock.lock()和lock.unlock删除同步块的第一部分是简单,因为我只需要调用lock()方法。问题是对notifyAll()和等待方法可以做什么。
Eq., the following code needs to be converted to use Lock.lock() and lock.unlock The first part to remove the synchronized block is simple as I just need to call lock() method. The question is what can be done for the notifyAll() and wait methods.
synchronized( LOCK )
{
while( !Thread.interrupted() )
{
try
{
working = runRules();
if( !working )
LOCK.notifyAll();
LOCK.wait( working ? shortTimeout : longTimeout );
}
catch( final InterruptedException e )
{
Package.log.info( "Thread was interrupted. Exiting.", e );
return;
}
}
}
推荐答案
a href =http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html> 条件
java.util.concurrent.locks
包提供的
Use the Condition
s provided by the java.util.concurrent.locks
package:
final Object monitor = ...
...
synchronized (monitor) {
while (!condition) monitor.wait();
... do something ...
}
p>
becomes:
final ReentrantLock lock = ...;
final Condition cvar = lock.newCondition();
...
lock.lock();
try {
while (!condition) cvar.await();
... do something ...
} finally {
lock.unlock();
}
信号端非常相似:
synchronized (monitor) {
... do something ...
monitor.notify();
}
变为:
lock.lock();
try {
... do something ...
cvar.signalAll();
} finally {
lock.unlock();
}
这篇关于转换等待& notifyAll代码使用Java 1.5 Lock对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!