Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to show multithreading using Runnable interface.

Java Code Example — Multithreading Programs

ADVERTISEMENT

Java Program to show multithreading using Runnable interface.

Objective

Write a Java program to create threads by implementing the Runnable interface.

Algorithm / Approach

  1. Create a class Test that implements Runnable.
  2. Provide an implementation for the run() method.
  3. In main, create instances of your Test class.
  4. Pass those instances into the constructor of the native Thread class (e.g., new Thread(t)).
  5. Call start() on the Thread objects.
Test.java
class Test implements Runnable {
 char x;
 Test(char a) {
  x = a;
 }
 public void run() {
  for(int i=0; i< 5; i++){
   System.out.println(x+""+i);
  }
 }
 public static void main(String[] a)
 {
  Test t = new Test('x');
  Test t2 = new Test('Y');
  Thread th1 = new Thread(t);
  Thread th2 = new Thread(t2);
  th1.start();
  th2.start();
 }
}

Expected Output

<b>Note:- Output will not be fixed</b>
Y0
x0
x1
Y1
x2
x3
x4
Y2
Y3
Y4

Explanation of the Program

  • Implementing the Runnable interface is the preferred way to create threads in Java.
  • Why? Because Java does not support multiple inheritance. If you extend Thread (like in the previous program), your class cannot extend any other class. By implementing Runnable, your class is free to extend another class if needed.
  • Notice that because Test is just a Runnable and not a Thread itself, it doesn't have a start() method. You must wrap it inside an actual Thread object to launch it.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT