Way2Java

Java Create Threads

Java Create Threads

Threads can be created in two ways in Java.

  1. By extending Thread class.
  2. By implementing Runnable interface.

Why Java requires two types and when to use which type, we will see later.

Signature of Thread class


public class Thread extends Object implements Runnable

Observe, the Thread class implements Runnable interface.

1. Creating a thread by extending Thread class

To create a thread, the first style and used generally is by extending Thread class.

Read the following program and see how simple to create a thread in Java. The program prints 0 to 9 numbers with a gap of 1000 milliseconds (1 second); it is the simplest way to create and control the thread.

public class Demo extends Thread
{
  public void run()        
  {
    try  
    {
      for(int i = 0; i < 10 ; i++) 
      {
	System.out.println("Welcome to threads: " + i);    
        Thread.sleep(1000);        
      }                                       
    }          
    catch(InterruptedException e)  
    {  
      System.err.println("Sleep time is disturbed, you may get incorrect functionality.  " + e);
    }
    System.out.println("Successful");   
  }
  public static void main(String args[])
  {
    Demo d1 = new Demo();
    d1.start();
  }
}

In the above program, Demo class extends Thread. To create a thread in Java, just extend Thread class and create an object, the object becomes a thread implicitly. Now, d1 is a thread of Demo class. Actually, d1 is an object of Demo class but we are calling it as a thread (because Demo extends Thread). This is how Java makes thread manipulation easy to the programmer; some more concepts that are made easy, we get later.

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

The thread, d1, is created, occupies some memory, but still it is inactive. An inactive thread is not eligible for microprocessor time even if the processor is idle. To make the thread active, call start() method on the thread. Now, d1 becomes active and eligible for a time-slice. start() is a method of Thread class. Forgetting to call the start() method makes the thread to die in inactive state itself without performing the job assigned.

public void run()

Whenever the thread is started, the first and foremost job it does is calling the run() method. It is a predefined thread of Thread class. This method is the heart of the thread and whatever code is expected to run by the thread should be put here. When the execution of run() method is over, the thread dies implicitly; naturally, its job is over.

Thread.sleep(1000);

sleep() is a method of Thread class inherited from Runnbale interface and overridden.

sleep() method signature

public static native void sleep(long milliseconds) throws InterruptedException

It is a static method throwing InterruptedException. Being a checked exception, whenever the sleep() method is used, the InterruptedException must be handled, else the code does not compile. The parameter 1000 is of long data type which indicates the inactive period of time in milliseconds. By calling sleep() method, the thread is made inactive for 1000 milliseconds (that is, 1 second). When the sleep time is over, the thread becomes implicitly active and eligible for microprocessor time (timeout of thread). For every iteration, the thread, d1, becomes inactive for 1000 milliseconds. sleep() is the easiest way to make the thread inactive and other ways we see later.

Java Create Threads

2. Creating a thread by implementing Runnable interface

Now, we write another program, with the same functionality (printing 0 to 9 with an interval of 1000 milliseconds), but implementing Runnable interface instead of the earlier Thread class.

public class Demo implements Runnable     		  
{
  public void run()        
  {
    try  
    {
      for(int i=0; i<10; i++)    
      {
	System.out.println("Welcome to threads: " + i);    
        Thread.sleep(1000);        
      }                                       
    }          
    catch(InterruptedException e)  
    {  
      System.err.println("Sleep time is disturbed, you may get incorrect functionality.  " + e);
    }
    System.out.println("Successful");   
  }
  public static void main(String args[])    
  {
    Demo d1 = new Demo();
    Thread t1 = new Thread(d1);
    t1.start();              
  }
}

In the above program, the object, d1, is not implicitly a thread because it is not extending Thread class; but implements Runnable interface. It takes one more statement to get the run() method executed.

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

Create an object, t1, of Thread class and pass the d1 object as parameter. Then, start the thread t1 with start() method. It indirectly calls the run() method of Demo class. This is extra work when Runnable interface is implemented instead of extending Thread class.

Java Create Threads: Extends vs Implements

When to use Thread or when to prefer Runnable. Even though no difference exists in the output, there is a reason and necessity to implement Runnable interface in some cases. If your class already extends another class like Frame or Applet, you cannot extend Thread class as Java does not support multiple inheritance. To overcome this problem, designers introduced another style of implementing Runnable interface. If your class does not extend another class, you can go for Thread class.

Java Create Threads: Why implementing Runnable approach is better than Thread extending?

In general, not exactly pertaining threads, when a method is called by an object, the JRE checks for overloaded methods exist or not, super class method is overridden or not (especially when a subclass object is assigned to super class object or reference variable) etc. It may be the same case with run() method of Thread class. If you implement Runnnable, JRE checks run() is implemented or not but does not check all the other round about rules. For this reason, everyone says implementing Runnable is speedier than Thread extends.