Java Reference
In-Depth Information
System.out.println("Ending main()");
return;
}
// Method where thread execution will start
public void run() {
try {
while(true) { // Loop indefinitely...
System.out.print(firstName); // Output first name
sleep(aWhile); // Wait aWhile msec.
System.out.print(secondName + "\n"); // Output second name
}
} catch(InterruptedException e) { // Handle thread interruption
System.out.println(firstName + secondName + e); // Output the exception
}
}
}
If you compile and run the code, you'll see something like this:
Press Enter when you have had enough...
Hopalong Marilyn Slim Cassidy
Hopalong Monroe
Marilyn Cassidy
Hopalong Pickens
Slim Monroe
Marilyn Cassidy
Hopalong Cassidy
Hopalong Monroe
Marilyn Pickens
Slim Cassidy
Hopalong Monroe
Marilyn Cassidy
Hopalong Cassidy
Hopalong Monroe
Marilyn Pickens
Slim Cassidy
Hopalong Cassidy
Hopalong Monroe
Marilyn
Enter pressed...
Ending main()
How It Works
There are three instance variables in our class TryThread and these are initialized in the constructor.
The two String variables hold first and second names, and the variable aWhile stores a time period
in milliseconds. The constructor for our class, TryThread() , will automatically call the default
constructor, Thread() , for the base class.
Search WWH ::




Custom Search