AppDividend
Latest Code Tutorials

Runnable Interface in Java Example | Java Runnable Interface

0

Runnable Interface in Java Example | Java Runnable Interface is today’s topic. In Java, the concept of multiple inheritance is possible only through the interface. The interface is a collection of abstracts method (normal method not present). Unless the class that implements the interface is abstract, all the method of the interface needs 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 that is 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 implements Runnable interface. There is no need for subclassing Thread when the task can be done by overriding only run() method of Runnable.

See the syntax interface.

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 multi-threaded program contains two or more lightweight parts that can run simultaneously. These parts of the multi-threaded program are called thread. Each thread has a different flow of execution.

In the starting 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 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 has to placed inside the method that we want to execute by the thread. Runnable interface is used for the creation of threads in Java. There are two ways by which thread can be generated in java the one of way is – Creating 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 Runnable

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

Any class whose instance needs to be executed by the thread should implement the Runnable interface.

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 that there are two methods to create a thread in java. One method, where we create a thread by extending from thread class is very limited 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. 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. 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 let one thread to wait until another thread completes its execution. It stops an 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 thread t2 and t3 was stopped until the thread t1 dies. 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.

Finally, Runnable Interface in Java Example | Java Runnable Interface Tutorial is over.

Leave A Reply

Your email address will not be published.

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