Home » Java Basics » 06 - Threads and GUIs
6

Thread Start()

How to start a thread

There are two ways of starting a new thread (i.e. spawning a thread from the main thread). One way is to make the application or class a subclass of the Thread Object, such as in the following:

public class HelloWorldThread extends Thread {
public void run() {
System.out.println("Hello World from Thread ");
}
 
public static void main(String args[]) {
(new HelloWorldThread()).start();
System.out.println("Hello World from Main Thread");
}
}

Note that the above class is a subclass of Thread. The main thread creates a new thread and invokes the 'start' method on the newly created thread. The newly created thread immediately starts execution of the run() method (all newly created threads execute the code in a run method); while the original thread continues execution in the main method. If a new object of some other type was created and a method of this object was invoked instead of '(new HelloWorldThread()).start()', the invoked method would complete execution before control flows to the System.out.println in the main method. However, if you save the above class and run it, you will likely see the main thread's 'Hello World' output display before the thread's output. This is because the newly created thread starts execution and runs along with the main thread. Another way to accomplish the same effect would be to implement the Runnable interface in the following way:

public class HelloWorldRunnable implements Runnable {
public void run() {
System.out.println("Hello From the Thread!");
}
public static void main(String args[]) {
(new Thread(new HelloWorldRunnable())).start();
System.out.println("Hello World from Main Thread");
}
}

The above class's main thread also creates a new Thread and invokes the Thread's start method. However, the constructor takes an instance the containing class (which implements the runnable interface) as an argument. Using the runnable interface provides flexibility to the developer. A class that implements Runnable is not restricted to being a subclass of thread unlike a class that extends Thread (a class may extend just one superclass; in addition, it can implement an unlimited number of interfaces).

Note: Do not associate a main method with the main thread; they are two different things. The main method is a part of the application; the main thread is the environment on which the application starts execution.