Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
new MyThread(cb, "X");
new MyThread(cb, "Y");
new MyThread(cb, "Z");

}


The following output will be produced. (The precise order in which the threads execute
may vary.)


Starting
A
B
C
Barrier Reached!
X
Y
Z
Barrier Reached!

As the preceding example shows, theCyclicBarrieroffers a streamlined solution to what
was previously a complicated problem.


Exchanger

Perhaps the most interesting of the synchronization classes isExchanger. It is designed
to simplify the exchange of data between two threads. The operation of anExchangeris
astoundingly simple: it simply waits until two separate threads call itsexchange( )method.
When that occurs, it exchanges the data supplied by the threads. This mechanism is both
elegant and easy to use. Uses forExchangerare easy to imagine. For example, one thread
might prepare a buffer for receiving information over a network connection. Another
thread might fill that buffer with the information from the connection. The two threads
work together so that each time a new buffer is needed, an exchange is made.
Exchangeris a generic class that is declared as shown here:


Exchanger<V>

Here,Vspecifies the type of the data being exchanged.
The only method defined byExchangerisexchange( ), which has the two forms
shown here:


V exchange(Vbuffer) throws InterruptedException

V exchange(Vbuffer, longwait, TimeUnittu)
throws InterruptedException, TimeoutException

Here,bufferis a reference to the data to exchange. The data received from the other thread is
returned. The second form ofexchange( )allows a time-out period to be specified. The key
point aboutexchange( )is that it won’t succeed until it has been called on the sameExchanger
object by two separate threads. Thus,exchange( )synchronizes the exchange of the data.


Chapter 26: The Concurrency Utilities 799

Free download pdf