Way2Java

Create and Start thread start() Example Java

Starting Thread start() is very easier in Java. It is the occasion to prove that Java is simple to practice. Just extend Thread to your class and create an object of your class. The object is nothing but a thread of your class. Start reading.

In Java, a thread can be created in two ways.

a) by extending Thread class
b) by implementing Runnable interface

The following example gives how to create thread and start the thread. Let us learn through an example thread start().
public class Demo extends Thread
{
  public void run()           
  {
    System.out.println("From run() method");
  }      
  public static void main(String args[])
  {
    Demo d1 = new Demo();
    d1.start();
  }
}

Demo d1 = new Demo();
d1.start();

In the above code, you say d1 is an object of Demo class. You are right; but at the same time, d1 is a thread of Demo class. It is so because Demo class extends Thread class. Observe, it is so simple to create a thread in Demo class. Just extend the class and create an object. The object becomes thread automatically.

The thread d1 is created but it is inactive. An inactive thread is not eligible for microprocessor time. To make the thread active, call start() method on the thread as d1.start(). start() method is defined in Thread class.

The start() method implicitly calls run() method. run() method is a concrete (non-abstract) method of Thread class. That is, calling start() method calls automatically run() method. This is the job of JVM. run() is the heart of the thread and any code you would like to be executed by the thread, write in the run() method.

Do not think of calling d1.run() directly. Thread looses lot of activities implicitly done by JVM.

You may be interested to know Difference between thread start() and run()