Java Program to create thread by implementing runnable interface

Program

class RunnableThread implements Runnable
{
	public void run()
	{
		System.out.println("Printing from run():\t" + Thread.currentThread().getName());
	}
}
public class ThreadImplementInterface
{
	public static void main(String[] args)
	{
		System.out.println("Threads: Implementing Runnable Interface");
		RunnableThread runnable = new RunnableThread();
		Thread thread = new Thread(runnable);
		System.out.println("Printing from main:\t" + Thread.currentThread().getName());
		thread.start();
	}
}

This Java program demonstrates creating a thread by implementing the Runnable interface.

  1. Runnable Interface:

    • A class RunnableThread implements the Runnable interface.
    • The Runnable interface requires the implementation of the run() method, which defines the task to be executed by the thread.
    • In the run() method, the program prints a message along with the current thread's name using Thread.currentThread().getName().
  2. Main Class:

    • The main class, ThreadImplementInterface, contains the main() method where the program begins execution.
    • It first prints a message: "Threads: Implementing Runnable Interface."
  3. Thread Creation:

    • An instance of RunnableThread is created and assigned to a variable runnable.
    • This Runnable instance is passed as an argument to the constructor of the Thread class to create a thread (thread).
    • The Runnable interface is used to separate the task definition (run()) from the thread implementation.
    • Using the Runnable interface is useful when a class needs to inherit from another class, as Java does not support multiple inheritance.
  4. Thread Execution:

    • Thread class is used to manage and control thread execution.
    • The start() method of the Thread class is called to begin execution of the thread.
    • When start() is called, the run() method of the Runnable instance is executed in a separate thread.
  5. Output:

    • The main thread prints its name using Thread.currentThread().getName(), which is typically "main".
    • The new thread executes the run() method, printing its thread name.

Output

Threads: Implementing Runnable Interface
Printing from main:	main
Printing from run():	Thread-0