HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

4) Multithreading Lesson

Java Threads: Implement Runnable Interface

11 min to complete · By Ryan Desmond

One of the two ways you can create a Thread in Java is by implementing the Runnable interface.

How to Implement the Runnable Interface

You can create a Thread using any object that implements the Runnable interface. The Runnable interface defines a single abstract method, run(). As this is an abstract method in the Runnable interface, you must override it and provide a method body.

The code inside the run() method will be what is executing when the Thread is created. Inside the run() method, you can create objects, call methods, and do anything else you could do with any other method. The run() method is the entry point for the Thread (It's kind of like the main() method but just for that unique Thread). When the code inside the run() method completes, the Thread is terminated.

Why Implementing Runnable is Preferred

Implementing Runnable is the preferred method of creating Threads

Unless you need to modify and override a specific behavior in the Thread class, it is best not to extend Thread. As all classes in Java are only able to extend one other class, this one extends is highly valuable, and you don't want to waste it if you don't need to be a subclass of Thread.

The only reason you would need to be a subclass of Thread is if you wanted to inherit attributes from the Thread class or override a given behavior in the Thread class. So that you can save this one extends for other uses (which you often need), the best option for us to create a new Thread is often by implementing Runnable

Multithreading Example using Runnable

Below is an example of implementing the Runnable class. When doing so, you must implement the one abstract method in the Runnable interface: The run() method.

package multi_threading.examples;

/*example controller used to 
demonstrate creating threads */
class ExampleController{
  public static void main(String[] args) {

    System.out.println("** Main Thread Start **");

    MyFirstRunnable threadTest = new MyFirstRunnable("MyFirstRunnable");
    MyFirstRunnable threadTest2 = new MyFirstRunnable("MySecondRunnable");
    MyFirstRunnable threadTest3 = new MyFirstRunnable("MyThirdRunnable");

    System.out.println("** Main Thread End **");
  }
}

class MyFirstRunnable implements Runnable {
    /* the Thread class is still required as 
        it is what spawns the thread */
  Thread thread;

  /* constructor that takes in a name for the thread */
  public MyFirstRunnable(String name) {

  /* create the Thread object - pass "this" object and 
      the name given - the Thread class has many 
      constructors you can choose from 
      this is just one example*/
  thread = new Thread(this, name);

  /* start the thread automatically when 
      the MyFirstRunnable object is created */
  thread.start();
}

  /* The run() method will be called automatically 
      after thread.start(). The start() method in the 
      Thread class will automatically invoke this run() 
      method upon initialization. All code inside the 
      run() method is what will run in a separate thread */
  @Override
  public void run() {
    System.out.println(thread.getName() + " starting.");
      try {
        for(int count=0; count<10; count++) {
         /* put this thread to sleep for 400 milliseconds */
        Thread.sleep(400);
        System.out.println("In " + thread.getName() + ", count is " + count);
      }
    }
    /* catch the potential exception */
    catch(InterruptedException exc) {
      System.out.println(thread.getName() + " interrupted.");
    }
    System.out.println(thread.getName() + " terminating.");
  }
}

In the code above, you are creating three distinct threads using the Runnable interface. There are many ways to create threads. This is just one example.

In this example, you are automatically creating the Thread object inside the constructor of MyFirstRunnable. You pass in "the runnable" which in this case is the class MyFirstRunnable (which implements Runnable), to the constructor of the Thread class. There are many constructors to choose from in the Thread class. You can see the one you're using in the image below:

A picture of the code for the Thread constructor that takes a target and name as parameters.

Here are a few more examples of how to start a new Thread using a class that implements Runnable. In this example, you do not automatically create the Thread in the Runnable constructor, but rather you rely on the user to create the Thread on their own and pass it in the Runnable.

class Temp{
  public static void main(String[] args) {
    System.out.println("** Main Thread Start **");

    // Option 1 -
    // 1: create the Runnable
    // 2: then create the Thread and pass it the Runnable and a Thread name
    // 3: start the Thread
    MySecondRunnable runnable1 = new MySecondRunnable();
    Thread thread1 = new Thread(runnable1, "Option 1");
    thread1.start();

    // Option 2
    // 1: Create the Thread and pass in the Runnable 
    // on the fly in the constructor as well as a Thread name
    // 2: start the Thread
    Thread thread2 
       = new Thread(new MySecondRunnable(), "Option 2");
    thread2.start();

    // Option 3
    // since you don't need an object of the Thread 
    // class you can actually just do it like this
    // create the Thread and Runnable on the fly, 
    // pass in the name and start it all on one line
    new Thread(new MySecondRunnable(), "Option 3").start();
    System.out.println("** Main Thread End **");
  }
}

class MySecondRunnable implements Runnable {

  @Override
  public void run() {
    System.out.println(
      Thread.currentThread().getName() + " starting.");
    try {
      for(int count=0; count<10; count++) {
          /* put this thread to sleep for 400 milliseconds */
          Thread.sleep(400);
          System.out.println("In " + 
            Thread.currentThread().getName() + 
            ", count is " + count);
      }
    }
    /* catch the potential exception */
    catch(InterruptedException exc) {
      System.out.println(
        Thread.currentThread().getName() + " interrupted.");
    }

    System.out.println(
      Thread.currentThread().getName() + " terminating.");
  }
}

Summary: How to Create Java Threads with Java Runnable

  • Java threads can be created by implementing the Runnable interface
  • Any class can use implements Runnable`
  • run() is an abstract method inside of Runnable and must be overridden
  • Implementing the Runnable interface is typically the preferred way to create threads