Implementing Runnable Interface

The Runnable interface in Java is a functional interface defined in the java.lang package. It is designed to be implemented by classes whose instances are intended to be executed by a thread.

Here’s the declaration of the Runnable interface:

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

The Runnable interface contains a single abstract method called run(), which represents the task or code that the implementing class needs to execute when it is executed as a thread. The run() method has no arguments and does not return a value.

  • To use the Runnable interface, you need to follow these steps:
  • Create a class that implements the Runnable interface.
  • Implement the run() method with the code or task you want the thread to execute.
  • Instantiate a Thread object and   an instance of your Runnable implementation as a constructor argument.
  • Call the start() method on the Thread object to start the thread and execute the run() method.

Here’s an example that demonstrates how to use the Runnable interface:

class MyRunnable implements Runnable {
    @Override
    public void run() {
		int i=1;
		while(i<10){
			System.out.println("Thread is running");
			i++;
		}	
    }
}
public class RunnableThread {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

Output:

D:\>javac RunnableThread.java

D:\>java RunnableThread

Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Code language: CSS (css)

In this example, we create a class ThreadDemo with a main method. Inside the main method, we create an instance of a class MyRunnable, which implements the Runnable interface. We then create a Thread object and pass the MyRunnable instance as a constructor argument.

Finally, we call the start() method on the Thread object to start the thread. As a result, the run() method of the MyRunnable instance will be executed in a separate thread.

When you run this program, you’ll see that the thread starts and executes the run() method, which simply prints “Thread is running”.

Using the Runnable interface provides a way to separate the task logic from the thread management, allowing for better code organization and reusability.

References

CodeGPT-small-java
Codebert-base
CodeBERT
Scroll to Top