Java Reference
In-Depth Information
Figure 15.1
Sample output of the RunnableDemo program.
Extending the Thread Class
You can create a thread by writing a class that extends the java.lang.Thread
class and overrides the run() method in Thread. To demonstrate, the following
GuessANumber class extends Thread and randomly picks a number between
1 and 100 until it guesses the int stored in the field number.
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ “ guesses “ + guess);
counter++;
}while(guess != number);
System.out.println(“** Correct! “ + this.getName()
Search WWH ::




Custom Search