Java - Specifying Your Code for a Thread

Introduction

There are three ways you can specify your code to be executed by a thread:

  • By inheriting your class from the Thread class
  • By implementing the Runnable interface in your class
  • By using the method reference to a method that takes no parameters and returns void

Inheriting Your Class from the Thread Class

class MyThreadClass extends Thread {
        @Override
        public void run() {
                System.out.println("Hello Java thread!");
        }
        ...
}

Create a thread object and start the thread are the same.

MyThreadClass myThread = new MyThreadClass();
myThread.start();

The thread will execute the run() method of the MyThreadClass class.

Implementing the Runnable Interface

You can create a class that implements the java.lang.Runnable interface.

Runnable is a functional interface and it is declared as follows:

@FunctionalInterface
public interface Runnable {
        void run();
}

You can use a lambda expression to create an instance of the Runnable interface.

Runnable aRunnableObject = () -> System.out.println("Hello Java thread!");

Then create an object of the Thread class using the constructor that accepts a Runnable object.

Thread myThread = new Thread(aRunnableObject);

Start the thread by calling the start() method of the thread object.

myThread.start();

The thread will execute the code contained in the body of the lambda expressions.

Using a Method Reference

You can use the method reference that takes no parameters and returns void as the logic for thread.

The following code declares a ThreadTest class that contains an execute() method which contains the code to be executed in a thread.

class ThreadTest {
     public static void execute() {
                System.out.println("Hello Java thread!");
     }
}

The following code uses the method reference of the execute() method of the ThreadTest class to create a Runnable object:

Thread myThread = new Thread(ThreadTest::execute);
myThread.start();

Example

The following code prints integers from 1 to 5 in a new thread.

A method reference is used to create the thread object in the example.

Demo

public class Main {
  public static void main(String[] args) {
    // Create a Thread object
    Thread t = new Thread(Main::print);

    // Start the thread
    t.start();//from www.ja va 2 s.  c  o m
  }

  public static void print() {
    for (int i = 1; i <= 5; i++) {
      System.out.print(i + " ");
    }
  }
}

Result

Related Topic