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, the CyclicBarrier offers a streamlined solution to what
was previously a complicated problem.
Exchanger
Perhaps the most interesting of the synchronization classes is Exchanger. It is designed
to simplify the exchange of data between two threads. The operation of an Exchanger is
astoundingly simple: it simply waits until two separate threads call its exchange( ) method.
When that occurs, it exchanges the data supplied by the threads. This mechanism is both
elegant and easy to use. Uses for Exchanger are 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.
Exchanger is a generic class that is declared as shown here:
Exchanger<V>
Here, V specifies the type of the data being exchanged.
The only method defined by Exchanger is exchange( ), which has the two forms
shown here:
V exchange(V buffer) throws InterruptedException
V exchange(V buffer, long wait, TimeUnit tu)
throws InterruptedException, TimeoutException
Here, buffer is a reference to the data to exchange. The data received from the other thread is
returned. The second form of exchange( ) allows a time-out period to be specified. The key
point about exchange( ) is that it won't succeed until it has been called on the same Exchanger
object by two separate threads. Thus, exchange( ) synchronizes the exchange of the data.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home