Java Threads Introduction
In this page:
class ClassName extends Thread {
public void run() {
// thread code
}
}
new ClassName().start();
What is a Thread?
A thread is a lightweight sub-process that executes concurrently inside your application, sharing the same memory space as every other thread in that process. This shared memory makes threads far cheaper to create than separate processes, enabling fast, non-blocking background work like network calls or file I/O.
Example: What is a Thread?
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws InterruptedException {
// Create a new Thread object and store it in t
Thread t = new Thread(() -> System.out.println("Running in background thread"));
// Start the thread; it runs in parallel with this code
t.start();
// Wait for the thread to finish
t.join();
}
}
Login to try C/C++/Java/PHP code in the editor
The Thread Class
You can declare a custom thread by extending the built-in Thread class and overriding its run() method with the code that should execute in the background. This approach is straightforward but ties up your only chance at inheritance, since Java classes can only extend one parent.
Example: The Thread Class
// Define the class Main
public class Main {
// Define the class MyThread
static class MyThread extends Thread {
public void run() {
// Print a line to the console
System.out.println("Custom thread running");
}
}
// Program entry point: the JVM starts running here
public static void main(String[] args) throws InterruptedException {
// Create a new MyThread object and store it in t
MyThread t = new MyThread();
// Start the thread; it runs in parallel with this code
t.start();
// Wait for the thread to finish
t.join();
}
}
Login to try C/C++/Java/PHP code in the editor
Starting a Thread
To actually start a thread, you initialize your Thread object and call its start() method rather than calling run() directly. Calling start() registers the thread with the JVM's scheduler, which then decides when to actually execute the run() method on a separate call stack.
Example: Starting a Thread
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> System.out.println("Executed via start()"));
t.start(); // registers with JVM scheduler
t.join();
}
}
Login to try C/C++/Java/PHP code in the editor
Main Thread Overview
Every Java program begins execution with a single main thread automatically created by the JVM before your main() method even runs. You can inspect and interact with this thread at any point using Thread.currentThread(), which is handy for logging or debugging concurrency issues.
Example: Main Thread Overview
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
Thread current = Thread.currentThread();
// Print a line to the console
System.out.println("Running on: " + current.getName());
}
}
Login to try C/C++/Java/PHP code in the editor
Multi-threaded Execution
By spawning multiple threads, a program can execute distinct tasks concurrently and take advantage of multiple CPU cores instead of running everything sequentially on one. This is especially valuable for CPU-bound work that can be split into independent chunks, or I/O-bound work that would otherwise leave a core idle while waiting.
Example: Multi-threaded Execution
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws InterruptedException {
// Create a new Thread object and store it in t1
Thread t1 = new Thread(() -> System.out.println("Task 1"));
// Create a new Thread object and store it in t2
Thread t2 = new Thread(() -> System.out.println("Task 2"));
// Start the thread; it runs in parallel with this code
t1.start();
// Start the thread; it runs in parallel with this code
t2.start();
// Wait for the thread to finish
t1.join();
// Wait for the thread to finish
t2.join();
}
}
Login to try C/C++/Java/PHP code in the editor
- Calling
t.run()instead oft.start(), which just runs the code in the current thread instead of creating a new one. - Calling
start()twice on the sameThread, which throws anIllegalThreadStateException. - Assuming threads print in a fixed order, when the scheduler decides, so output can differ between runs unless you use
join()or synchronization.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: