Java Program to demonstrate multithreading using Thread class.
Objective
Write a Java program to demonstrate multithreading by extending the Thread class.
Algorithm / Approach
- Create a class
Testthatextends Thread. - Override the
run()method and write a loop that prints a character 5 times. - In the
mainmethod, create two instances of theTestclass. - Call the
start()method on both instances to begin execution.
Test.java
class Test extends Thread {
char x;
Test(char a){
x = a;
}
public void run() {
for(int i = 0; i< 5; i++) {
System.out.println(i+" "+x);
}
}
}
class Main {
public static void main(String[] a)
{
Test t =new Test('A');
Test t2 = new Test('X');
t.start();
t2.start();
}
}
Expected Output
<b>Note:- Output will not be fixed</b> 0 X 0 A 1 X 1 A 2 X 3 X 2 A 4 X 3 A 4 A
Explanation of the Program
- Multithreading allows a program to perform multiple tasks concurrently (at the same time), maximizing CPU utilization.
- When you extend the
Threadclass, you MUST override therun()method. This method contains the code that the new thread will execute. - Crucially, you must call
start(), NOTrun(), to begin the thread. Callingstart()tells the JVM to allocate a new call stack for the thread and then the JVM automatically callsrun(). If you callrun()directly, it executes sequentially on the main thread, defeating the purpose of multithreading.
Complexity
Time Complexity
O(n) - For the loops.
Space Complexity
O(1) - Thread allocation depends on JVM.