Java Create Thread using Runnable Interface Example

Java Thread Examples


In this article, we will learn how to create and run a thread using the Runnable interface in a Java application.

Java provides two ways to create a thread programmatically.
  1. Implementing the Runnable interface.
  2. Extending the Thread class.
In this post, we will focus on creating thread using the Runnable interface with an example.

Java Create Thread using Runnable Interface Example

The Runnable interface defines a single method, run(), meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor.
Let's demonstrate how to use the Runnable interface with an example.
First, create a Task or WorkerThread using the Runnable interface.

WorkerThread.java

public class WorkerThread implements Runnable {
    private String data;
 
    public WorkerThread(final String anyData) {
       this.data = anyData;
    }
 
    @Override
    public void run() {
       for (int i = 0; i < 5; i++) {
           System.out.println("[" + Thread.currentThread().getName() + "] [data=" + 
           this.data + "] Message " + i);
           try {
               Thread.sleep(200);
           } catch (final InterruptedException e) {
               e.printStackTrace();
           }
      }
   }
}
Second, let's see how to use the WorkerThread class in the main thread. In this example, the main() method is the main thread which will create another using Above WorkerThread class.
public class InstantiateUsingRunnable {
 
    public static void main(final String[] args) {
  
        System.out.println("Thread main started");
  
        final Thread thread1 = new Thread(new WorkerThread("Process data through Runnable interface")); 
        thread1.start();
        thread1.setName("Demo Thread");
  
        System.out.println("Thread main finished");
    }
}
Output:
Thread main started
Thread main finished
[Demo Thread] [data=Process data through Runnable interface] Message 0
[Demo Thread] [data=Process data through Runnable interface] Message 1
[Demo Thread] [data=Process data through Runnable interface] Message 2
[Demo Thread] [data=Process data through Runnable interface] Message 3
[Demo Thread] [data=Process data through Runnable interface] Message 4


Comments