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
RunnableThread
implements theRunnable
interface. - The
Runnable
interface 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
RunnableThread
is created and assigned to a variablerunnable
. - This
Runnable
instance is passed as an argument to the constructor of theThread
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.
- An instance of
-
Thread Execution:
Thread
class is used to manage and control thread execution.- The
start()
method of theThread
class is called to begin execution of the thread. - When
start()
is called, therun()
method of theRunnable
instance 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