Java Reference
In-Depth Information
Thread first = new Thread(new JumbleNames("Hopalong ", "Cassidy
", 200L));
Thread second = new Thread(new JumbleNames("Marilyn ", "Monroe ",
300L));
Thread third = new Thread(new JumbleNames("Slim ", "Pickens ",
500L));
// Set threads as daemon
first.setDaemon(true);
second.setDaemon(true);
third.setDaemon(true);
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.err.println(e);
// Output the
exception
}
System.out.println("Ending main()");
return;
}
private String firstName;
// Store for
first name
private String secondName;
// Store for
second name
private long aWhile;
// Delay in
milliseconds
}
JumbleNames.java
How It Works
You have the same data members in this class as you had in the previous example. The constructor is al-
most the same as previously, too. You can't call
setDaemon()
in this class constructor because the class
isn't derived from
Thread
. Instead, you need to do that in
main()
after you've created the objects that
represent the threads and before you call the
run()
method. The
run()
method implementation is also
very similar. The class doesn't have
sleep()
as a member, but because it's a
public static
member of
the
Thread
class, you can call it in the
run()
method by using the class name as the qualifier.