[英]Regarding Notify()
我正在遍歷線程,並且讀到notify()
方法用於將信號發送到同一對象的等待池中正在等待的線程中的僅一個。 notifyAll()
方法的工作方式與notify()
相同,只是方法將信號發送給所有在Object
上等待的線程。
現在,我的查詢是,假設我有5個線程和一個主線程,那么首先啟動主線程,然后再啟動其他五個線程。 現在我只想發送通知到第三線程。 使用notify()
怎么可能,因為在這里我僅向第三線程發送通知? 請指教。
如果要通知特定線程,則讓它在其他對象上wait()
,然后在該對象上調用notify()
。
通過允許每個對象多個等待集, ReentrantLock類為您提供比synchronized
關鍵字更精細的控制。
您可以使用ReentrantLock.newCondition()
從ReentrantLock獲取多個條件 。 然后,線程可以調用Condition.await()
(功能類似於Object.wait()
),並阻塞直到另一個線程調用Condition.signal()
(功能類似於Object.notify()
)。
區別在於您可以為單個ReentrantLock
創建多個Conditions
。 因此,您可以為每個Thread
創建一個Condition
,然后在與您要喚醒的Thread
相對應的條件下調用signal()
。
這是演示上述內容的簡單示例代碼。 它創建5個Threads
,它們都在同一ReentrantLock
不同Conditions
下等待。 然后,主線程調用signal()
來喚醒Threads
的特定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
喚醒Thead 3號
3號線程醒了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.