☕ Java
Creating Threads in Java
A thread is an independent path of execution. Multithreading lets your program do multiple things simultaneously — handle requests while processing data, download files while updating the UI, run tasks in parallel to finish faster.
Why Multithreading?
Without threads, your program is single-threaded — one thing happens at a time. If you're downloading a large file, the UI freezes. If you're processing a batch of data, you can't respond to user input.
Real-world analogy: A restaurant with one waiter vs. many waiters. One waiter handles one table at a time — everyone else waits. Multiple waiters handle multiple tables simultaneously — everyone gets served faster.
Java's multithreading lets you spawn multiple "workers" (threads) to run concurrently on multiple CPU cores.
Two Ways to Create Threads
Java gives you two approaches. Runnable is preferred in modern code because it separates the task (what to do) from the thread (the worker), and it works with thread pools.
Java
// Way 1: Extend Thread class
// Simple, but you've used up your single inheritance slot
class DownloadTask extends Thread {
private String url;
DownloadTask(String url) { this.url = url; }
@Override
public void run() {
System.out.println(getName() + " downloading: " + url);
// ... actual download logic
}
}
// Way 2: Implement Runnable (preferred)
// Keeps task logic separate from thread management
class ImageProcessor implements Runnable {
private String imagePath;
ImageProcessor(String path) { this.imagePath = path; }
@Override
public void run() {
System.out.println(Thread.currentThread().getName()
+ " processing: " + imagePath);
}
}
// Starting threads
DownloadTask t1 = new DownloadTask("https://example.com/file.zip");
t1.start(); // start() creates a new thread and calls run()
Thread t2 = new Thread(new ImageProcessor("photo.jpg"));
t2.start();
// Java 8+ — Lambda thread (most concise, great for short tasks)
Thread t3 = new Thread(() -> System.out.println("Quick background task done!"));
t3.start();Thread Lifecycle
A thread moves through these states:
1. NEW — Thread object created, start() not called yet
2. RUNNABLE — Running or waiting for its turn on a CPU core
3. BLOCKED — Waiting to acquire a lock held by another thread
4. WAITING — Paused, waiting for another thread to signal it (Object.wait())
5. TIMED_WAITING — Paused for a specific duration (Thread.sleep(1000))
6. TERMINATED — run() has finished (normally or via exception)
Key thread methods:
• start() — begins execution (never call run() directly — that runs in the current thread!)
• sleep(ms) — pause the current thread for X milliseconds
• join() — wait for another thread to finish before continuing
• interrupt() — signal a thread to stop what it's doing