Java Reference
In-Depth Information
as it is created. In the case of
MyThread
, this is done by instantiating a
Thread
object in-
side
MyThread
's constructor. Second, there is no need for
MyThread
to store the name
of the thread since it is possible to give a name to a thread when it is created. To do so, use
this version of
Thread
's constructor:
Thread(Runnable
threadOb
, String
name
)
Here,
name
becomes the name of the thread.
Ask the Expert
Q
:
You state that in a multithreaded program, one will often want the main thread
to finish last. Can you explain?
A
:
The main thread is a convenient place to perform the orderly shutdown of your pro-
gram, such as the closing of files. It also provides a well-defined exit point for your
program. Therefore, it often makes sense for it to finish last. Fortunately, as you will
soon see, it is trivially easy for the main thread to wait until the child threads have
completed.
You can obtain the name of a thread by calling
getName( )
defined by
Thread
. Its gen-
eral form is shown here:
final String getName( )
Although not needed by the following program, you can set the name of a thread after it
is created by using
setName( )
, which is shown here:
final void setName(String
threadName
)
Here,
threadName
specifies the name of the thread.
Here is the improved version of the preceding program: