Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate multithreading using Thread class.

Java Code Example — Multithreading Programs

ADVERTISEMENT

Java Program to demonstrate multithreading using Thread class.

Objective

Write a Java program to demonstrate multithreading by extending the Thread class.

Algorithm / Approach

  1. Create a class Test that extends Thread.
  2. Override the run() method and write a loop that prints a character 5 times.
  3. In the main method, create two instances of the Test class.
  4. 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 Thread class, you MUST override the run() method. This method contains the code that the new thread will execute.
  • Crucially, you must call start(), NOT run(), to begin the thread. Calling start() tells the JVM to allocate a new call stack for the thread and then the JVM automatically calls run(). If you call run() 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.
ADVERTISEMENT