Java thread implements Runnable


Java thread implements Runnable

Once you know thread basics, know how to create threads in Java. Java comes with two styles of creating threads.

1. Thread creation by extending Thread class
2. Thread creation by implementing Runnable interface

You have seen earlier, the first style of creation of thread. Now let us go for the second style.

Aim: To create, start and execute thread by implementing Runnable interface. The execution should print 0 to 9 numbers with an interval of 1000 milliseconds (1 second).

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();              
  }
}

Java thread implements Runnable

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.

Leave a Comment

Your email address will not be published.