我正在浏览线程,我读到notify()方法用于向同一对象的等待池中等待的一个且只有一个线程发送信号。方法notifyAll()的工作方式与notify()相同,只是它将信号发送到等待Object的所有线程。
现在我的问题是,假设我有5个线程和一个主线程,那么最初主线程启动,然后其他5个线程启动。现在我只想向第三个线程发送通知。既然我在这里只向第三个线程发送通知,使用notify()怎么可能呢?请给我建议。
发布于 2012-04-15 12:11:20
如果你想通知一个特定的线程,让它在不同的对象上执行wait(),然后在这个对象上调用notify()。
发布于 2012-04-15 13:15:10
通过允许每个对象有多个等待集,ReentrantLock类为您提供了比synchronized关键字更细粒度的控制。
您可以使用ReentrantLock.newCondition()从一个ReentrantLock获取多个Conditions。然后,一个线程可以调用Condition.await() (在功能上类似于Object.wait()),并将阻塞,直到另一个线程调用Condition.signal() (功能上类似于Object.notify())。
不同之处在于您可以为单个ReentrantLock创建多个Conditions。因此,您可以为每个Thread创建一个Condition,并在与您想要唤醒的Thread相对应的条件下调用signal()。
下面是一个简单的示例代码,它演示了上面的内容。它创建了5个Threads,它们都在同一个ReentrantLock的不同Conditions上等待。然后,主线程调用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被唤醒了!
https://stackoverflow.com/questions/10159399
复制相似问题