Java Reference
In-Depth Information
System.out.println("Press Enter when you have had enough...\n");
first.start(); // Start the first thread
second.start(); // Start the second thread
third.start(); // Start the third thread
try {
System.in.read(); // Wait until Enter key pressed
System.out.println("Enter pressed...\n");
} catch (IOException e) { // Handle IO exception
System.out.println(e); // Output the exception
}
System.out.println("Ending main()");
return;
}
}
How It Works
We have the same data members in this class as we had in the previous example. The constructor is
almost the same as previously. We can't call
setDaemon()
in this class constructor because our class
isn't derived from
Thread
. Instead, we need to do that in
main()
after we've created the objects
representing the threads. The
run()
method implementation is also very similar. Our class doesn't
have
sleep()
as a member, but because it's a
public
static
member of the class
Thread
, we can
call it in our
run()
method by using the class name.
In the method
main()
, we still create a
Thread
object for each thread of execution, but this time we
use a constructor that accepts an object of type
Runnable
as an argument. We pass an object of our
class
JumbleNames
to it. This is possible because our class implements
Runnable
.
Thread Names
Threads have a name, which in the case of the
Thread
constructor we're using in the example, will be a
default name composed of the string
"Thread*"
with a sequence number appended. If you want to
choose your own name for a thread, you can use a
Thread
constructor that accepts a
String
object
specifying the name you want to assign to the thread. For example, we could have created the
Thread
object
first
with the statement:
Thread first = new Thread(new JumbleNames ("Hopalong ", "Cassidy ", 200L),
"firstThread");
This assigns the name
"firstThread"
to the thread. Note that this name is only used when displaying
information about the thread. It has no relation to the identifier for the
Thread
object, and there's
nothing, apart from common sense, to prevent several threads being given the same name.
You can obtain the name assigned to a thread by calling the
getName()
method for the
Thread
object. The
name of the thread is returned as a
String
object. You can also change the name of a thread by calling the
setName()
method defined in the class
Thread
and passing a
String
object to it.
Once we've created the three
Thread
objects in the example, we call the
setDaemon()
method for
each. The rest of
main()
is the same as in the original version of the previous example, and you should
get similar output when you run this version of the program.