Multithreading is a Java feature that allows multiple threads to execute within the same program. A thread is a lightweight unit of execution.
Multithreading is useful for tasks such as downloading files, processing data, handling user requests, and running background operations while the main program continues.
A thread is a separate path of execution inside a program.
Every Java application starts with a main thread that
executes the main() method.
public class Main {
public static void main(String[] args) {
System.out.println("Main thread is running");
}
}
Main thread is running
In this example, the main thread executes the
statement inside the main() method.
One way to create a thread is to extend the
Thread class and override its
run() method.
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
Thread is running
start() starts a new thread, which then
executes the run() method.
run() directly does not start a new
thread. Use start() to begin a separate
thread of execution.
Another common approach is to implement the
Runnable interface. This separates the
task from the thread that runs it.
class MyTask implements Runnable {
public void run() {
System.out.println("Runnable task is running");
}
}
public class Main {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread t1 = new Thread(task);
t1.start();
}
}
Runnable task is running
Implementing Runnable is often preferable
when your class needs to extend another class.
You can create multiple threads to perform different tasks. The JVM and operating system determine when each thread executes.
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(
Thread.currentThread().getName() + ": " + i
);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
Thread-0: 1
Thread-1: 1
Thread-0: 2
Thread-0: 3
Thread-1: 2
Thread-1: 3
The Thread.sleep() method pauses the
current thread for a specified time. The duration is
measured in milliseconds.
public class Main {
public static void main(String[] args)
throws InterruptedException {
for (int i = 1; i <= 3; i++) {
System.out.println(i);
Thread.sleep(1000);
}
}
}
1
2
3
The program pauses for approximately one second after each printed number.
Thread.sleep() can throw
InterruptedException. This example declares
it using throws InterruptedException.
The join() method makes the calling thread
wait until the specified thread finishes.
class MyThread extends Thread {
public void run() {
System.out.println("Child thread finished");
}
}
public class Main {
public static void main(String[] args)
throws InterruptedException {
MyThread t1 = new MyThread();
t1.start();
t1.join();
System.out.println("Main thread continues");
}
}
Child thread finished
Main thread continues
Because the main thread calls join(),
it waits for t1 to finish before printing
the second message.
Java allows you to set thread names and priorities. Priorities are scheduling hints and do not guarantee execution order.
class MyThread extends Thread {
public void run() {
System.out.println(
"Thread name: " + Thread.currentThread().getName()
);
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.setName("WorkerThread");
t1.setPriority(Thread.NORM_PRIORITY);
t1.start();
}
}
Thread name: WorkerThread
Java provides these common priority constants:
Thread.MIN_PRIORITY — 1Thread.NORM_PRIORITY — 5Thread.MAX_PRIORITY — 10A Java thread can move through several states during its lifetime.
| State | Description |
|---|---|
NEW |
The thread has been created but not started. |
RUNNABLE |
The thread is ready to run or is running. |
BLOCKED |
The thread is waiting to acquire a monitor lock. |
WAITING |
The thread is waiting indefinitely for another action. |
TIMED_WAITING |
The thread is waiting for a limited time. |
TERMINATED |
The thread has finished execution. |
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args)
throws InterruptedException {
MyThread t1 = new MyThread();
System.out.println(t1.getState());
t1.start();
t1.join();
System.out.println(t1.getState());
}
}
NEW
Thread is running
TERMINATED
When multiple threads access shared data, their
operations may interfere with each other. The
synchronized keyword can protect a
critical section so only one thread at a time executes
it using the same monitor lock.
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args)
throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.getCount());
}
}
2000
Both threads share the same counter. Synchronization protects the increment operation from lost updates.
The volatile keyword helps ensure that
threads see the latest value of a shared variable.
It does not make compound operations such as
count++ atomic.
class SharedData {
volatile boolean running = true;
}
public class Main {
public static void main(String[] args)
throws InterruptedException {
SharedData data = new SharedData();
Thread worker = new Thread(() -> {
while (data.running) {
// Wait while running is true.
}
System.out.println("Worker stopped");
});
worker.start();
Thread.sleep(100);
data.running = false;
worker.join();
}
}
Worker stopped
Here, the volatile field allows the worker thread to observe the updated flag. In real applications, avoid busy-waiting when a more suitable coordination method is available.
For many applications, an executor is a better way to manage tasks than manually creating a new thread for every task. An executor can reuse threads from a pool.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor =
Executors.newFixedThreadPool(2);
executor.submit(() -> {
System.out.println("Task 1 is running");
});
executor.submit(() -> {
System.out.println("Task 2 is running");
});
executor.shutdown();
}
}
Task 1 is running
Task 2 is running
shutdown() stops accepting new tasks while
allowing submitted tasks to finish.
| Method | Purpose |
|---|---|
start() |
Starts a new thread of execution. |
run() |
Contains the task executed by a thread. |
sleep() |
Pauses the current thread for a specified time. |
join() |
Waits for another thread to finish. |
getName() |
Gets the thread name. |
setName() |
Sets the thread name. |
getState() |
Returns the current thread state. |
isAlive() |
Checks whether a thread has started and not yet terminated. |
Thread class.Runnable interface.Thread.sleep() to pause a thread for one second.join() to make the main thread wait for a worker thread.ExecutorService to execute three tasks.Select the correct answer for each question.