Java is a powerful, multi-threaded programming language that allows you to run multiple tasks simultaneously. This guide will help you understand how to create and manage threads in Java, using both the Thread
class and the Runnable
interface.
1. What Is a Thread?
A thread is a lightweight sub-process, the smallest unit of processing. Threads share the same memory space but can execute independently. Java makes it easy to work with threads through the java.lang.Thread
class and the java.lang.Runnable
interface.
2. Ways to Create a Thread in Java
- By extending the
Thread
class - By implementing the
Runnable
interface - Using lambda expressions (Java 8+)
- Using the
ExecutorService
framework
3. Method 1: Extending the Thread Class
This is one of the simplest ways to create a thread. You subclass the Thread
class and override its run()
method.
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running using Thread class.");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // start the thread
}
}
start()
instead of run()
to initiate a new thread.4. Method 2: Implementing the Runnable Interface
Another popular and more flexible approach is implementing the Runnable
interface. This is useful when your class needs to extend another class.
Example:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running using Runnable interface.");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
5. Method 3: Using Anonymous Inner Classes
You can create threads using anonymous classes for quick one-time usage.
Example:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println("Thread using anonymous class.");
}
});
thread.start();
}
}
6. Method 4: Using Lambda Expressions (Java 8+)
Lambdas offer a clean and concise way to create threads.
Example:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread using lambda expression.");
});
thread.start();
}
}
7. Method 5: Using ExecutorService
ExecutorService
is part of the java.util.concurrent package and offers a higher-level replacement for managing threads manually.
Example:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
System.out.println("Thread using ExecutorService.");
});
executor.shutdown();
}
}
8. Thread Life Cycle in Java
- New: Thread instance created but not started.
- Runnable: Thread is ready to run but waiting for CPU time.
- Running: Thread is currently executing.
- Blocked/Waiting: Waiting for monitor lock or signal.
- Terminated: Thread has finished execution or was stopped.
9. Thread Methods You Should Know
start()
– starts the threadrun()
– contains the code to executesleep()
– pause executionjoin()
– wait for thread to finishisAlive()
– check if thread is runningsetPriority()
– set thread priority
Example Using sleep and join:
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
System.out.println("Thread finished after 1 second.");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
thread.join(); // wait for thread to finish
System.out.println("Main thread ends.");
}
}
10. Best Practices
- Prefer
Runnable
orExecutorService
over subclassingThread
. - Always use
start()
instead ofrun()
. - Handle exceptions within threads properly.
- Use synchronization when accessing shared resources.
11. Real-World Use Case
Let’s simulate downloading files in parallel using threads:
Example:
class DownloadTask implements Runnable {
private String fileName;
public DownloadTask(String fileName) {
this.fileName = fileName;
}
public void run() {
System.out.println("Downloading " + fileName + "...");
try {
Thread.sleep(2000); // simulate download delay
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(fileName + " downloaded.");
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new DownloadTask("file1.zip"));
Thread t2 = new Thread(new DownloadTask("file2.zip"));
Thread t3 = new Thread(new DownloadTask("file3.zip"));
t1.start();
t2.start();
t3.start();
}
}
12. Conclusion
Java provides a rich set of tools to create and manage threads, enabling you to build responsive and scalable applications. Whether you’re building simple multi-threaded programs or