Java represents a thread as an object. An object of the java.lang.Thread class represents a thread.
There are at least two steps involved in working with a thread:
We can use the default constructor of the Thread class to create a Thread object.
Thread simplestThread = new Thread();
We must call its start() method to start the thread represented by that object.
simplestThread.start();
There are three ways you can specify your code to be executed by a thread:
When we inherit class from the Thread
class,
we should override the run() method and provide the code to be executed by the thread.
class MyThreadClass extends Thread { @Override public void run() { System.out.println("Hello Java thread!"); } }
The steps to create a thread object and start the thread.
MyThreadClass myThread = new MyThreadClass();
myThread.start();
The thread will execute the run() method of the MyThreadClass class.
We 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(); }
From Java 8, we can use a lambda expression to create an instance of the Runnable interface.
Runnable aRunnableObject = () -> System.out.println("Hello Java thread!");
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.
From Java 8, we can use the method reference of a method of any class that takes no parameters and returns void as the code to be executed by a thread.
The following code declares a ThreadTest class that contains an execute() method.
The method contains the code to be executed in a thread.
public 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();
The thread will execute the code contained in the execute() method of the ThreadTest class.
The following code shows how to create a thread and print integers from 1 to 5 on the standard output.
public class Main { public static void main(String[] args) { // Create a Thread object Thread t = new Thread(Main::print); //w w w. j a v a 2 s . co m // Start the thread t.start(); } public static void print() { for (int i = 1; i <= 5; i++) { System.out.print(i + " "); } } }
The code above generates the following result.