Java Reference
In-Depth Information
}
}
Listing6-2
'
smainthreadfirstcreatesapairofcountdownlatches.The
startSig-
nal
countdownlatchpreventsanyworkerthreadfromproceedinguntilthemainthread
is ready for them to proceed. The
doneSignal
countdown latch causes the main
thread to wait until all worker threads have finished.
Themainthreadnextcreatesarunnablewhose
run()
methodisexecutedbysubse-
quently created worker threads.
The
run()
methodfirstoutputsaninitialmessageandthencalls
startSignal
's
await()
methodtowaitforthiscountdownlatch'scounttoreadzerobeforeitcanpro-
ceed. Oncethishappens,
run()
outputsamessage that indicates workisbeingdone,
and sleeps for a random period of time (0 through 999 milliseconds) to simulate this
work.
Atthispoint,
run()
invokes
doneSignal
's
countDown()
methodtodecrement
this latch's count. Once this count reaches zero, the main thread waiting on this signal
will continue, shutting down the executor and terminating the application.
After creating the runnable, the main thread obtains an executor that's based on a
thread pool of
NTHREADS
threads, and then calls the executor's
execute()
method
NTHREADS
times,passingtherunnabletoeachofthe
NTHREADS
pool-basedthreads.
This action starts the worker threads, which enter
run()
.
Next,themainthreadoutputsamessageandsleepsforonesecondtosimulatedoing
additionalwork(givingalltheworkerthreadsachancetohaveentered
run()
andin-
voke
startSignal.await()
),invokes
startSignal
's
countdown()
method
tocausetheworkerthreadstostartrunning,outputsamessagetoindicatethatitisdoing
somethingelse,andinvokes
doneSignal
's
await()
methodtowaitforthiscount-
down latch's count to reach zero before it can proceed.
When you run this application, you will observe output similar to the following:
main thread doing something
1312936533890:
Thread[pool-1-thread-1,5,main]:
entered
run()
1312936533890:
Thread[pool-1-thread-2,5,main]:
entered
run()
1312936533890:
Thread[pool-1-thread-3,5,main]:
entered
run()
1312936534890: Thread[pool-1-thread-1,5,main]: doing work