One of the two ways to use a thread in Java is to extend the Thread object. It can be done like the following.
public class ExtendThread extends Thread {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
ExtendThread thread = new ExtendThread();
thread.start();
System.out.println("This code is outside of the thread");
}
}
public void run() {
System.out.println("This code is running in a thread");
}
}
Of course this is only good if you are not extending another Class.
You must override the run
method, and you will need to call start()
to start the thread and it’s task. Everything that is to be done in the Thread, needs to be in, or called from the run command. Often there is a loop to keep the thread running, but that is not always the case.
There is a loop in this example, to show that you cannot always assume one action will be performed before another. Check to see the output of this example and how it may vary from execution to execution.
Java – Extending Thread was originally found on Access 2 Learn
One Comment
Comments are closed.