Java Multithreading/Concurrency
Source: Dev.to
What is multithreading in Java?
Multithreading in Java is a feature that allows for the concurrent execution of two or more parts of a program, known as threads, to maximize CPU utilization. Each thread can run in parallel with others, sharing the same memory space.
Key Concepts
- Thread – A lightweight sub‑process, the smallest unit of processing. Multiple threads can exist within a single process.
- Concurrency vs. Parallelism
- Concurrency – Multiple threads make progress in an interleaved manner on a single CPU core. The system switches between threads, giving the illusion of simultaneous execution.
- Parallelism – Multiple threads run simultaneously on different CPU cores, achieving true parallel execution.
- Main Purpose
- Performance – Execute CPU‑intensive tasks in parallel, speeding up execution on multi‑core processors.
- Responsiveness – Keep an application responsive; long‑running tasks (e.g., network requests or file downloads) can run in a background thread without freezing the UI.
How to Create Threads in Java
There are two primary ways to create a thread.
Implementing the Runnable Interface (Preferred)
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running by implementing Runnable.");
}
}
// To start the thread:
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Extending the Thread Class
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running by extending Thread.");
}
}
// To start the thread:
MyThread thread = new MyThread();
thread.start();
Thread States
In Java, a thread can be in one of the following states, defined in java.lang.Thread.State:
-
NEW – The thread has been created but not yet started.
-
RUNNABLE – The thread is executing in the JVM (either currently running or ready to run, awaiting scheduler selection).
-
BLOCKED – The thread is waiting to acquire a monitor lock to enter a synchronized block or method.
-
WAITING – The thread is waiting indefinitely for another thread to perform a particular action. It enters this state by calling:
Object.wait(); // no timeout Thread.join(); // no timeout LockSupport.park(); -
TIMED_WAITING – The thread is waiting for a specified period of time. It enters this state by calling methods with a timeout, such as:
Thread.sleep(long millis); Object.wait(long timeout); Thread.join(long millis); LockSupport.parkNanos(long nanos); LockSupport.parkUntil(long deadline); -
TERMINATED – The thread has completed its execution, either by finishing the
run()method normally or by throwing an unhandled exception.