Java Reference
In-Depth Information
■
Inheriting your class from the
Thread
class may not be possible if your class already inherits from another
class. In that case, you will need to use the second method. You can use the third method from Java 8. Before Java 8,
it was common to use an anonymous class to define a thread object where the anonymous class would either inherit
from the
Thread
class or implement the
Runnable
interface.
Tip
Inheriting Your Class from the Thread Class
When you inherit your class from the
Thread
class, you should override the
run()
method and provide the code to be
executed by the thread.
public class MyThreadClass extends Thread {
@Override
public void run() {
System.out.println("Hello Java thread!");
}
// More code goes here
}
The steps to 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();
}
From Java 8, you 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.