How to create threads in Java

  • 05 April 2016
  • ADM

 

How to create threads in Java - images/logos/java.jpg

 

In order to create a thread the application need to provide the code that will be executed within that thread. There are two ways of creating a thread:

  • extend the class Thread;
  • implement the interface Runnable.

Example 1 - extend class Thread

The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the example below.

package com.admfactory.threads;

public class ThreadExample1 extends Thread {
    
    @Override
    public void run() {
        System.out.println("Hello from thread created using Thread class!");
    }

}

Example 2 - implement interface Runnable

The Runnable interface defines a single method, run, meant to contain the code executed in the thread.

package com.admfactory.threads;

public class ThreadExample2 implements Runnable {
    
    @Override
    public void run() {
        System.out.println("Hello from thread created using Runnable interface!");
    }

}

Test

Below are the tests for both implementations.

package com.admfactory.threads;

public class ThreadTests {
    public static void main(String[] args) throws Exception {
        
        System.out.println("Testing threads - START!");

        /** Starting the thread directly - the class extends Thread class */
        Thread thread1 = new ThreadExample1();
        thread1.start();

        /**
         * Starting the thread by passing as parameter to Thread class - the
         * class implements Runnable interface
         */
        Thread thread2 = new Thread(new ThreadExample2());
        thread2.start();
        
        /** wait 3 seconds to finish both threads */
        Thread.sleep(3000);

        System.out.println("Testing threads - FINISH!");
    }

}

Output

Testing threads - START!
Hello from thread created using Thread class!
Hello from thread created using Runnable interface!
Testing threads - FINISH!

Both implementations runs in a similar way.

Comparison

Using Thread class you create the object and is ready to be executed by invoking start method. Using Runnable interface you need to create the object and pass it to a Thread object in order to be started.

The questions is which of these two approaches should I use?

  • Thread: it is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread.
  • Runnable: it is a more general way to execute tasks. It is more flexible and separates the Runnable task from the Thread object that executes the task.

 

References