UseString(Exchanger<String> c) {
ex = c;
new Thread(this).start();
public void run() {
for(int i=0; i < 3; i++) {
try {
// Exchange an empty buffer for a full one.
str = String());
System.out.println("Got: " + str);
} catch(InterruptedException exc) {
Here is the output produced by the program:
In the program, the main( ) method creates an Exchanger for strings. This object is then
used to synchronize the exchange of strings between the MakeString and UseString classes.
The MakeString class fills a string with data. The UseString exchanges an empty buffer for
a full one. It then displays the contents of the newly constructed string. The exchange of
empty and full buffers is synchronized by the exchange( ) method, which is called by both
class' run( ) method.
Using an Executor
The concurrent API supplies a feature called an executor that initiates and controls the
execution of threads. As such, an executor offers an alternative to managing threads
through the Thread class.
At the core of an executor is the Executor interface. It defines the following method:
void execute(Runnable thread)
The thread specified by thread is executed. Thus, execute( ) starts the specified thread.
The ExecutorService interface extends Executor by adding methods that help manage and
control the execution of threads. For example, ExecutorService defines shutdown( ), shown
here, which stops the invoking ExecutorService.
void shutdown( )
ExecutorService also defines methods that execute threads that return results, that execute
a set of threads, and that determine the shutdown status. We will look at several of these
methods a little later.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks