Java Reference
In-Depth Information
Note Afterwaitingthreadsarereleased,subsequentcallsto await() returnimme-
diately.Also,becausethecountcannotbereset,a CountDownLatch instancecanbe
usedonlyonce.Whenrepeateduseisarequirement,usethe CyclicBarrier class
instead.
We can use CountDownLatch to ensure that worker threads start working at ap-
proximately the same time. For example, check out Listing 6-2 .
Listing 6-2. Using a countdown latch to trigger a coordinated start
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class CountDownLatchDemo
{
final static int NTHREADS = 3;
public static void main(String[] args)
{
final
CountDownLatch
startSignal
=
new
Coun-
tDownLatch(1);
final
CountDownLatch
doneSignal
=
new
Coun-
tDownLatch(NTHREADS);
Runnable r = new Runnable()
{
public void run()
{
try
{
report("entered run()");
startSignal.await(); // wait
until told to proceed
report("doing work");
Thread.sleep((int)(Math.random()*1000));
doneSignal.countDown(); // re-
duce count on which
//
 
Search WWH ::




Custom Search