Multithreading is one of the most powerful features in Java that allows multiple tasks to run simultaneously. It helps improve performance and makes programs faster and more efficient.
In this guide, you’ll learn how multithreading works using a simple and clear example with Thread1 and Thread2.
What is Multithreading?
Multithreading is a process where multiple threads run concurrently within a single program.
A thread is a lightweight process that performs a specific task.
For example, a web browser can download files while playing videos at the same time — this is multithreading.
Why Use Multithreading?
- Improves performance
- Efficient CPU utilization
- Faster execution
- Better user experience
Creating Threads in Java
There are two main ways to create threads:
- By extending
Threadclass - By implementing
Runnableinterface
In this example, we’ll use the Thread class.
Multithreading Program Example (Thread1 & Thread2)
Let’s create two threads that run simultaneously and print messages.
class Thread1 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread1: " + i);
try {
Thread.sleep(500);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
class Thread2 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread2: " + i);
try {
Thread.sleep(500);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
public class TestThreads {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}
}
Output
Thread1: 1 Thread2: 1 Thread1: 2 Thread2: 2 Thread1: 3 Thread2: 3 ...
The output may vary because threads run independently.
How This Program Works
- Thread1 and Thread2 extend the Thread class
- Each thread overrides the
run()method start()method begins execution- Both threads run concurrently
Important Methods in Thread Class
start()→ starts threadrun()→ contains logicsleep()→ pauses threadjoin()→ waits for thread to finish
Real-World Use Cases
- Web servers
- Gaming applications
- Video streaming
- Background tasks
Common Mistakes
- Calling run() instead of start()
- Ignoring exceptions
- Not synchronizing shared data
Best Practices
- Use Runnable for better flexibility
- Handle exceptions properly
- Avoid unnecessary threads
FAQ
What is multithreading?
Running multiple threads simultaneously in a program.
What is a thread?
A lightweight process that executes a task.
What is difference between start() and run()?
start() creates a new thread, run() executes normally.
Conclusion
Multithreading is essential for building fast and responsive Java applications. The Thread1 and Thread2 example clearly shows how multiple threads can run at the same time.
Practice this concept with different programs to strengthen your understanding.

Comments
Post a Comment