Java Reference
In-Depth Information
Tip Multiple threads can wait on the same lock (same phone number to be
awakened). When a secondary thread calls notify, it will wake up one of the “waiting”
threads (there is no fairness about which is awakened). Sometimes you will need to no-
tify all the threads; you can call the notifyAll() method instead of calling the no-
tify() method. This is mostly used when preparing many threads to take some work,
but the work is not yet finished setting up.
Solution 2 uses a more modern approach to notification, as it involves a Coun-
tDownLatch . When setting up, specify how many “counts” the latch will have. The
main thread will then wait (stop execution) by calling the CountDownLatch 's
await() method until the latch counts down to 0 . When the latch reaches 0 , the main
thread will wake up and continue execution. As the worker thread completes, call the
latch.countdown() method, which will decrement the latch's current count
value. If the latch's current value reaches 0 , the main thread that was waiting on the
CountDownLatch will wake up and continue execution.
The main advantage of using CountDownLatches is that it is possible to spawn
multiple tasks at the same time and just wait for all of them to complete. (In the solu-
tion example, we didn't need to wait until one or the other thread were completed be-
fore continuing; they all were started, and when the latch was 0 , the main thread con-
tinued.)
Solution 3 instead offers a solution in which we have access to the thread we want
to wait on. For the main thread, it's just a matter of calling the secondary thread's
join() method. Then the main thread will wait (stop executing) until the secondary
thread completes.
The advantage of this method is that it doesn't require the secondary threads to
know any synchronization mechanism. As long as the secondary thread terminates exe-
cution, the main thread can wait on them.
10-8. Creating Thread-Safe Objects
Problem
You need to create an object that is thread-safe because it will be accessed from mul-
tiple threads.
Search WWH ::




Custom Search