Runnable Interface in Java: The Complete Guide

0
36
Runnable Interface in Java Example | Java Runnable Interface

In Java, the concept of multiple inheritance is possible only through the interface. The interface is a collection of abstracts (standard method not present). Unless the class that implements the interface is abstract, all the interface methods need to be defined in the class. A class implements an interface using the keyword implements.

Runnable interface in Java

The Java.lang.Runnable is the interface to be implemented by the class whose instances are intended to be executed by a thread. There are two ways to start a new Thread – Subclass Thread and implement the Runnable interface.

There is no need for subclassing Thread when the task can be done by overriding only the run() method of Runnable.

Syntax

class <class_name> implements <interface_name>

See the following code example.

//creating an interface 
interface java 
{
  static final String lan = "Java";  
  public void display();
}
 
 //driver class 
public class example implements java 
{
  public static void main(String []args) 
  {
    example obj = new example();
    obj.display();
  }
  public void display() 
  {
    System.out.println(lan + " is a programming language");
  }
}

See the output.

Runnable Interface in Java

Thread in Java

Java provides support for multithreaded programming. A multithreaded program contains two or more lightweight parts that can run simultaneously. These parts of the multithreaded program are called a thread. Each thread has a different flow of execution.

At the start of every Java program, one thread begins running, which is called the main thread of the program because it is the one that is executed when the program is initiated.

Syntax

thread t = new thread (new RunnableTask ());
t.start();

See the following program.

public class threading extends Thread
{  
  public void run()
  {  
    System.out.println("Thread is running.");  
  }   
  public static void main(String args[])
  {  
     threading obj=new threading();   
     obj.start();  
  }  
}

See the following output.

Thread in Java

Runnable Interface

The Runnable interface is a basic Java Interface that comes with every Java platform. It outlines a class whose instances can execute as a thread. java.lang.Runnable interface only has a single method run().

The basic look of the Runnable interface.

public interface Runnable () {
   public void run ();
}

Run()

It is called when the thread is started. The code must be placed inside the method we want to execute by the thread. The runnable interface is used for the creation of threads in Java. There are two ways by which a thread can be generated in Java. One way is – To create a thread by implementing the runnable interface.

Steps to create a thread using Runnable

  1. Create a class that implements Runnable.
  2. Use the runnable method in the Runnable class.
  3. Create an instance of a thread class and pass our Runnable object to its constructor as the parameter. The thread object is created that can run the runnable class.
  4. Call the Thread object’s start method.

See the following code.

public class threading_2 implements Runnable
{  
  public void run()
  {  
    System.out.println("Thread is running.");  
  }   
  public static void main(String args[])
  {  
     threading_2 obj=new threading_2();  
     Thread t =new Thread(obj);  
     t.start();  
  }  
}

See the output.

Steps to create a thread using RunnableThe Runnable interface is a primary template for any object intended to be executed by the thread. It defines the single method run(), which is meant to contain a code executed by a thread.

The thread should implement the Runnable interface for any class whose instance needs to be executed.

A Thread class itself implements a Runnable with an empty implementation of a run() method.

For creating the new thread, create an instance of the class that implements the Runnable interface and then pass that instance to the Thread(Runnable target) constructor.

Runnable or Thread class, which is better?

As we already know, two methods exist to create a thread in Java. One method, where we create a thread by extending from a thread class, is minimal because once we extend our class from a thread, we cannot extend from any other class as Java doesn’t allow multiple inheritance.

So, generally, we should always use a runnable interface to create a thread. However, this method is quite flexible. It allows us to extend from any other class.

So, In general, You should always use the Runnable object to create a thread. However, this method is more flexible. It allows your class to extend from any other class. Also, you can use anonymous class syntax and Java 8’s lambda expression with Runnable to make your code more concise.

Joining Thread in Java

The Java.lang.thread class provides the join() method, which lets one thread wait until another thread completes its execution. It stops the execution of a current thread until the joined thread dies.

Syntax

public void join () throws InterruptedException
public void join (long milliseconds) throws InterruptedException                                                      

See the following code.

public class Joinmethod_ex extends Thread
{  
 public void run()
 {  
  for(int i=1;i<=5;i++)
  {  
   try
   {  
     Thread.sleep(500);  
   }
   catch(Exception e)
   {
     System.out.println(e);
   }  
   System.out.println(i);  
  }  
 }  
 public static void main(String args[])
 {  
    Joinmethod_ex t1=new Joinmethod_ex();  
    Joinmethod_ex t2=new Joinmethod_ex();  
    Joinmethod_ex t3=new Joinmethod_ex();  
    t1.start();  
    try
    {  
	t1.join();  
    }
    catch(Exception e)
    {
	System.out.println(e);
    }  
    t2.start();  
    t3.start();  
 } 
}

See the output.

Joining Thread in Java

As you can see in the above program, the execution of threads t2 and t3 was stopped until thread t1 died.

So, the join() method allows one thread to wait for the completion of the other. In the following example, Thread 2 waits for the completion of Thread 1 for 1000 milliseconds by calling Thread.join(1000), and then starts the execution.

That’s it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.