Thread
- Java course
- Advanced
- Lesson 55/82
- 5 min
Learn to create threads with Thread.
Thread
The Thread class represents a thread of execution in Java. A class can extend Thread and override run() to define a new thread.
class HelloThread extends Thread {
@Override
public void run() {
System.out.println("Hello");
}
}An instance of this class runs on a separate thread when start() is called. If run() is called directly, it executes like a normal method; this is useful for debugging. Java 21 supports platform threads and virtual threads.
Thread lifecycle
A Thread's main states are: NEW (created), RUNNABLE (running), BLOCKED (waiting), WAITING (waiting) and TERMINATED (done).
Thread t = new HelloThread();
System.out.println(t.getState());
// NEWWhen start() is called, the state becomes RUNNABLE. When the thread finishes, it is TERMINATED. getState() shows the current state. This is useful for debugging concurrency bugs.
Practice Write the HelloThread class
Define a HelloThread class that extends Thread and overrides run() with @Override. The run() body calls System.out.println("Hello from thread"). In a ThreadDemo class write a main method; create an instance of HelloThread and call run() directly (do not start).
Starter code
// Define HelloThread extending Thread
// Override run() and call println
// Write main in ThreadDemo and call run()Sample solution
class HelloThread extends Thread {
@Override
public void run() {
System.out.println("Hello from thread");
}
}
class ThreadDemo {
public static void main(String[] args) {
new HelloThread().run();
}
}Expected output
Hello from thread
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method is overridden to define a new Thread?
- start()
- join()
- run() Correct answer
- sleep()
Explanation: The thread body is defined in run().
2 Complete the Thread inheritance
class HelloThread ____ Thread {
@Override
public void run() {
System.out.println("Hello");
}
}
class HelloThread extends Thread {
@Override
public void run() {
System.out.println("Hello");
}
}
Explanation: extends is used to inherit from Thread.
3 Match Thread methods
| Term | Meaning |
|---|---|
start() |
Starts the new thread |
run() |
Defines the task body |
join() |
Waits for completion |
sleep(ms) |
Pauses for a duration |