Multithreading is a core feature of Java that enables concurrent execution of two or more parts of a program for maximum utilization of modern multi-core CPU hardware. A Thread is the smallest lightweight unit of dispatchable execution within a process.
java.lang.Thread Classclass WorkerThread extends Thread {
@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
WorkerThread t1 = new WorkerThread();
t1.setName("Worker-Alpha");
t1.start(); // Spawns new thread on OS!
}
}
java.lang.Runnable (Best Practice)Because Runnable is a @FunctionalInterface, it can be written cleanly as a lambda expression:
public class RunnableDemo {
public static void main(String[] args) {
// Lambda implementation of Runnable
Runnable task = () -> {
for (int i = 1; i <= 3; i++) {
System.out.println("Processing async step " + i + " on " + Thread.currentThread().getName());
}
};
Thread worker = new Thread(task, "BackgroundWorker");
worker.start();
}
}
Exam Question: "What happens if you invoke t.start() twice on the exact same Thread instance?"
Answer: The JVM throws java.lang.IllegalThreadStateException! A thread can only be started once in its entire lifecycle. Once it completes or starts, it cannot be restarted.
Now let us examine the 6 states of the Java Thread Lifecycle. Proceed to: Java Thread States & Lifecycle →
Accelerate your Java mastery by studying these tightly connected core tutorials:
NEW, RUNNABLE, BLOCKED states.
Preventing race conditions.
Thread pools in enterprise apps.
Modern lightweight concurrency.