There are following way to print even and odd numbers using two threads in Java.
- Create a TaskOddEven class extends thread class. this class is with argument constructor name and number.
- Now create first thread class object of reference t1 with argument string “Odd Thread : ” and 1 number.
- Now create first thread class object of reference t2 with argument string “Even Thread : ” and 2 number.
- When t1.start() call the run method, there we iterate the for loop from 0 to 4 number. inside this.number value will be increment with 1 and print the first Thread.
- Next t2.start() call the run method, there we iterate the for loop from 0 to 4 number. inside this.number value will be increment with 2 and print the second Thread.
class TaskOddEven extends Thread {
int number;
String name;
public TaskOddEven(String name, int number) {
this.name=name;
this.number = number;
}
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println(getName() + this.number);
this.number += 2;
}
}
}
public class PrintOddEven {
public static void main(String[] args) {
TaskOddEven t1 = new TaskOddEven("Odd Thread : ", 1);
TaskOddEven t2 = new TaskOddEven("Even Thread : ", 2);
t1.start();
t2.start();
}
}
Output :-
Odd Thread : 1
Odd Thread : 3
Odd Thread : 5
Odd Thread : 7
even Thread : 2
even Thread : 4
even Thread : 6
even Thread : 8