ReentrantLocksynchronized
类通过允许每个对象有多个等待集,为您提供比关键字更细粒度的控制。
您可以使用ReentrantLock从ReentrantLock获取多个条件。然后一个线程可能会调用(在功能上与 类似)并将阻塞直到另一个线程调用(在功能上与 类似)。ReentrantLock.newCondition()
Condition.await()
Object.wait()
Condition.signal()
Object.notify()
不同之处在于您可以Conditions
为单个ReentrantLock
. 因此,您可以Condition
为每个创建一个Thread
并调用与您想要唤醒signal()
的条件相对应的条件。Thread
这是一个演示上述内容的简单示例代码。它创建了 5 个Threads
,它们都等待不同Conditions
的相同ReentrantLock
。然后主线程调用signal()
以唤醒特定的Threads
.
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ReentranLockTest
{
public static void main( String[] args )
{
final ReentrantLock lock = new ReentrantLock( );
int numThreads = 5;
Condition[] conditions = new Condition[numThreads];
// start five threads, storing their associated Conditions
for ( int i = 0; i < numThreads; i++ )
{
final int threadNumber = i;
System.out.printf( "Started thread number %d%n", threadNumber );
// to create a Condition we must lock the associated ReentrantLock
lock.lock( );
try
{
final Condition condition = lock.newCondition( );
conditions[i] = condition;
// start the worker Thread
( new Thread( )
{
@Override
public void run( )
{
// wait on the Condition
// to do so we must be holding the
// associated ReentrantLock
lock.lock( );
try
{
condition.await( );
}
catch ( InterruptedException e )
{
e.printStackTrace( );
}
finally
{
lock.unlock( );
}
// print something when signal()
// is called on our Condition
System.out.printf( "Thread number %d woke up!%n", threadNumber );
}
} ).start( );
}
finally
{
lock.unlock( );
}
}
// acquire the ReentrantLock and call
// Condition.signal() to wake up Thread number 3
lock.lock( );
try
{
System.out.printf( "Waking up Thead number %d%n", 3 );
conditions[3].signal( );
}
finally
{
lock.unlock( );
}
}
}
这应该打印以下内容:
启动线程号 0
开始线程号 1
启动线程号 2
启动线程号 3
启动线程号 4
醒来头号 3
3号线程醒了!