Creating & Running Threads
Multithreading allows a program to run multiple tasks simultaneously. Java provides two ways to create threads: extending the Thread class or implementing the Runnable interface. This is essential for performance-critical applications.
45 min•By Priygop Team•Last updated: Feb 2026
Understanding Threads
A thread is a lightweight unit of execution within a program. Multiple threads can run concurrently, sharing the same memory space. This is useful for I/O operations, background tasks, and taking advantage of multi-core CPUs. Java manages threads through the Thread class and Runnable interface.
Creating Threads
Example
// Method 1: Extend Thread class
class DownloadThread extends Thread {
private String fileName;
DownloadThread(String fileName) {
this.fileName = fileName;
}
@Override
public void run() {
System.out.println("Downloading " + fileName + "...");
try {
Thread.sleep(2000); // Simulate download time
} catch (InterruptedException e) {
System.out.println("Download interrupted!");
}
System.out.println(fileName + " downloaded!");
}
}
// Method 2: Implement Runnable (preferred)
class PrintTask implements Runnable {
private String taskName;
private int count;
PrintTask(String taskName, int count) {
this.taskName = taskName;
this.count = count;
}
@Override
public void run() {
for (int i = 1; i <= count; i++) {
System.out.println(taskName + ": Step " + i + "/" + count);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
return;
}
}
System.out.println(taskName + " completed!");
}
}
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println("=== Starting Downloads ===");
// Create and start threads
DownloadThread d1 = new DownloadThread("image.jpg");
DownloadThread d2 = new DownloadThread("video.mp4");
Thread t3 = new Thread(new PrintTask("Analysis", 3));
d1.start(); // start(), not run()!
d2.start();
t3.start();
// Wait for all threads to finish
d1.join();
d2.join();
t3.join();
System.out.println("\nAll tasks completed!");
// Lambda syntax (Java 8+)
Thread quickTask = new Thread(() -> {
System.out.println("Quick task running on " + Thread.currentThread().getName());
});
quickTask.start();
}
}Try It Yourself: Parallel Counter
Try It Yourself: Parallel CounterJava
Java Editor
✓ ValidTab = 2 spaces
Java|40 lines|1456 chars|✓ Valid syntax
UTF-8