Java Reference
In-Depth Information
19
new Thread(new ThreadExample("Aloha")).start();
20
new Thread(new ThreadExample("Ciao")).start();
21
}
22
}
ThreadExample.java
1.
Declaration of implementation of the
Runnable
interface:
line 0
Since
ThreadExample
implements the
Runnable
interface, it can be passed to the construc-
tor of
Thread
.If
ThreadExample
fails to provide a
run()
method, the compiler will complain.
2.
Member variables and constructor:
lines 2-6
Each instance of
ThreadExample
contains its own greeting string.
3.
run()
:
lines 8-15
Loop forever performing:
Print the thread name and instance greeting:
line 10
The static method
Thread.currentThread()
returns a reference to the thread from
which it is called, and
getName()
returns a string containing the name of that thread.
Suspend thread:
lines 11-13
After printing its instance's greeting message, each thread sleeps for a random amount
of time (between 0 and 100 milliseconds) by calling the static method
Thread.sleep()
,
which takes the number of milliseconds to sleep as a parameter.
Math.random()
returns
a random
double
between 0.0 and 1.0.
Thread.sleep()
can be interrupted by another
thread, in which case an
InterruptedException
is thrown. Our example does not include
an interrupt call, so the exception will not happen in this application.
4.
main()
:
lines 17-21
Each of the three statements in
main()
does the following: 1) creates a new instance
of
ThreadExample
with a different greeting string, 2) passes this new instance to the
constructor of
Thread
, and 3) calls the new
Thread
instance's
start()
method. Each thread
independently executes the
run()
method of
ThreadExample
, while the
main()
thread
terminates. Note that the JVM does not terminate until all nondaemon (see
Thread
s API)
threads terminate.
Upon execution, an interleaving of the three greeting messages is printed to the console.
The exact interleaving of the numbers depends upon the factors mentioned earlier.
4.1.2 Server Protocol
Since the two server approaches we are going to describe (thread-per-client and thread pool)
are independent of the particular client-server protocol, we want to be able to use the same
protocol code for both. The code for the echo protocol is given in the class
EchoProtocol
,
which encapsulates the implementation of the server side of the echo protocol. The idea is
that the server creates a separate instance of
EchoProtocol
for each connection, and protocol
Search WWH ::
Custom Search