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.
-
Runnable Interface:
- A class
RunnableThreadimplements theRunnableinterface. - The
Runnableinterface requires the implementation of therun()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 usingThread.currentThread().getName().
- A class
-
Main Class:
- The main class,
ThreadImplementInterface, contains themain()method where the program begins execution. - It first prints a message: "Threads: Implementing Runnable Interface."
- The main class,
-
Thread Creation:
- An instance of
RunnableThreadis created and assigned to a variablerunnable. - This
Runnableinstance is passed as an argument to the constructor of theThreadclass to create a thread (thread). - The
Runnableinterface is used to separate the task definition (run()) from the thread implementation. - Using the
Runnableinterface is useful when a class needs to inherit from another class, as Java does not support multiple inheritance.
- An instance of
-
Thread Execution:
Threadclass is used to manage and control thread execution.- The
start()method of theThreadclass is called to begin execution of the thread. - When
start()is called, therun()method of theRunnableinstance is executed in a separate thread.
-
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.
- The main thread prints its name using
Output
Threads: Implementing Runnable Interface
Printing from main: main
Printing from run(): Thread-0