A thread is a single sequential flow of control within a program*. Programs can have multiple threads, and therefore multiple sequential flows of control. When multiple threads are used, multiple processes can take place at once.
Using a thread for each RaceCar, this program simulates a race between two RaceCars.
-------------------------------------------------------------------------
class Race {
public static void main (String[] args) {
/**
* Start two seperate threads. They finish their individual laps in
* random time intervals, calculated independently within each
* RaceCar.
* Because they are Threads, they run simultaneously.
*/
new RaceCar("Ferrari").start();
new RaceCar("Ranault").start();
}
}
-------------------------------------------------------------------------
class RaceCar extends Thread {
//Constructor sets the name of the car
public RaceCar(String name) {
super(name);
}
//Overwrites Thread run method
public void run() {
//Repeat loop 5 times
for (int lap = 1; lap < 6; lap++) {
try {
/**
* The sleep method is a Thread
* method used to suspend Thread operation.
* it is used here to generate the duration of each lap (between 0
* and 5000 milliseconds).
*/
//Math.random generates a double between 0 and 1.
sleep((int)(Math.random() * 5000));
} catch (InterruptedException e) {}
//print that run is completed
System.out.println("lap " + lap + " " + getName());
}
//print that RaceCar has finished all laps
System.out.println("FINISH! " + getName());
//stop is a Thread method that ends Thread operation.
stop();
}
}
*http://java.sun.com/docs/books/tutorial/essential/threads/definition.html
|