Introduction
Multithreading is a powerful concept in Java that allows programs to execute multiple threads simultaneously. Each thread runs independently, allowing for concurrent execution of tasks and better utilization of CPU resources. In this blog post, we’ll explore a simple multithreading example in Java and understand how threads work.
Java Multithreading Example
Program Description
The given Java program creates two threads, t1
and t2
, both of which extend the Thread
class. Each thread prints numbers from 0 to 4 with a delay of 1 second between each print. Additionally, thread t2
throws a runtime exception when i
reaches 3.
Java Code Explanation
Let’s break down the provided code:
public class Main {
public static void main(String[] args) {
ThreadingProgram t1 = new ThreadingProgram("t1");
ThreadingProgram t2 = new ThreadingProgram("t2");
t1.start();
t2.start();
}
}
class ThreadingProgram extends Thread {
String name;
ThreadingProgram(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread " + name + " is: " + i);
try {
if (this.name.equals("t2") && i == 3) {
throw new RuntimeException();
}
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
Explanation
1. Main Class (Main
)
main
Method:- Creates two instances of
ThreadingProgram
,t1
andt2
. - Starts both threads using the
start()
method.
2. ThreadingProgram Class
- Instance Variables:
name
: Stores the name of the thread (t1
ort2
).- Constructor:
- Initializes the
name
of the thread. run
Method (Thread Execution):- Overrides the
run()
method from theThread
class. - Iterates from 0 to 4 (
for (int i = 0; i < 5; i++)
). - Prints the current thread name (
"Thread " + name
) and the value ofi
. - Delays execution for 1 second (
Thread.sleep(1000)
) to simulate work. - Throws a
RuntimeException
fort2
wheni
equals 3, simulating an exceptional condition.
Execution Flow
- Thread
t1
: - Prints numbers 0 to 4 normally.
- Waits 1 second between each print.
- Thread
t2
: - Prints numbers 0 to 2 normally.
- Throws a
RuntimeException
wheni
is 3. - This stops further execution in
t2
due to the unhandled exception.
Key Concepts
- Thread Creation: Each instance of
ThreadingProgram
represents a separate thread of execution (t1
andt2
). - Thread Execution: The
run()
method defines the behavior of each thread. - Exception Handling: Demonstrates how exceptions can interrupt thread execution (
RuntimeException
thrown byt2
).
Conclusion
This example demonstrates the basics of multithreading in Java using a simple program with two threads. Understanding how threads operate concurrently and handle exceptions is essential for developing efficient and robust concurrent applications.
Feel free to experiment with this example by modifying the code or adding new features. If you have any questions or want to explore more advanced multithreading concepts, let me know!