Site icon TestingDocs.com

Java Runnable Interface

Overview

In this tutorial, we will learn about the Java Runnable Interface, which allows a Java application to run multiple threads. There are two ways to create a new thread of execution in Java.

One way is to declare a class to be a subclass of Thread. This subclass should override the run() method of class Thread. An instance of the subclass can then be allocated and started.

Let’s see another better approach to creating threads in Java applications.

Java Runnable Interface

The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run() method. An instance of the class can
then be allocated, passed as an argument when creating Thread, and started. The Thread class itself implements the Runnable interface.

public class Thread implements Runnable {

}

 

The java.lang.Runnable interface in Java is a functional interface representing a task or action that can be executed by a separate thread. It is defined in the java.lang package, which is the default package in Java.

The Runnable interface has a single abstract method, run(), which does not take any arguments and does not return any value. When a class implements the Runnable interface, it must provide an implementation for the run() method.

Example

A class that implements the Runnable interface and overrides the run() method.

package com.testingdocs.java.tutorials;

public class ParallelTask implements Runnable {

	@Override
	public void run() {
		System.out.println("In ParallelTask : Thread Name::" + Thread.currentThread().getName());
	}
}

Demo Program

package com.testingdocs.java.tutorials;

/**
 *
 * Java program to demonstrate Runnable interface
 * Java Tutorials - www.TestingDocs.com
 */

public class RunnableDemo {

	public static void main(String args[]) {
		System.out.println("Demo ");
		ParallelTask task1 = new ParallelTask();
		new Thread(task1).start(); //Start Thread
		ParallelTask task2 = new ParallelTask();
		new Thread(task2).start(); //Start Thread
	}
}

 

The demo application started two threads apart from the main thread.

Sample Output

Demo
In ParallelTask : Thread Name::Thread-0
In ParallelTask : Thread Name::Thread-1

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version