Skip to main content

Practical-39

Write a java program which use of Runnable Interface.


Introduction

The Runnable Interface is one of the building blocks of thread programs in Java. It is a functional interface which can be implemented using a lambda expression or by creating a separate class. Java's Runnable Interface provides a thread system with a way to handle executable tasks. This allows developers to spawn multiple pieces of code, running in parallel, and have a single entry point and the ability to interact with those threads.

Code

public class sample implements Runnable{
@Override
public void run(){
System.out.println("Thread started");
System.out.println("Current Thread: " +
Thread.currentThread().getName());
}

public static void main(String[] args) {
Thread t = new Thread(new sample(), "MyThread");
t.start();
}
}

Output

Thread started
Current Thread: MyThread
Explanation

The above code uses the Runnable Interface to create a new thread which is labelled "MyThread". The sample run() method is then called to print a simple message to the console.