Java Program to show multithreading using Runnable interface.
Objective
Write a Java program to create threads by implementing the Runnable interface.
Algorithm / Approach
- Create a class
Testthatimplements Runnable. - Provide an implementation for the
run()method. - In main, create instances of your
Testclass. - Pass those instances into the constructor of the native
Threadclass (e.g.,new Thread(t)). - Call
start()on theThreadobjects.
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
Runnableinterface 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 implementingRunnable, your class is free to extend another class if needed. - Notice that because
Testis just a Runnable and not a Thread itself, it doesn't have astart()method. You must wrap it inside an actualThreadobject to launch it.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)