ReentrantLockクラスは、オブジェクトごとに複数の待機セットを許可することにより、キーワードよりも細かい粒度制御を提供します。
ReentrantLockから複数のConditionsを取得するには、ReentrantLock.newCondition()
を使用します。スレッドはCondition.await()
(機能はObject.wait()
と同様)を呼び出し、別のスレッドがCondition.signal()
(機能はObject.notify()
と同様)を呼び出すまでブロックします。
ReentrantLock
に対して複数のConditions
を作成することができます。したがって、Thread
ごとにCondition
を作成し、目覚めたいThread
に対応する条件でsignal()
を呼び出してください。
ここでは、上記を示す簡単なコード例を示します。それは同じの別のすべてを待つ5 Threads
を作成します。ReentrantLock
。その後、メインスレッドはsignal()
を呼び出して、Threads
の特定の1つを起動します。
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は、目が覚めた
THEAD番号3を目覚めます!
こんにちは、ありがとうございます。あらかじめご理解いただける小さなプログラムを表示してください。1 – Neera
@ user1334074:1つの回答を受け入れ、仕事をしてください。 – Jayan
@ user1334074答えは完全にわかります。有能なJavaプログラマは、それをコードに変換できるはずです。 – EJP