Learn how to print even and odd numbers using two threads in Java with a simple multithreading example. In this example, we create separate threads for odd and even numbers.
Code Explanation (Step-by-Step)
- Create a TaskOddEven class that extends the Thread class. The class has a parameterized constructor that accepts the thread name and starting number.
- Create the first thread object t1 by passing “Odd Thread : ” as the name and 1 as the starting number.
- Create the second thread object t2 by passing “Even Thread : ” as the name and 2 as the starting number.
- Now Call start() to start the odd-number thread. The start() method causes the run() method to execute on a new thread.
- Inside the run() method, iterate the for loop four times. The number starts from 1 and is incremented by 2 after each iteration: 1, 3, 5, 7
- After Call start() to start the even-number thread. Its run() method also iterates four times.
- The even number starts from 2 and is incremented by 2 after each iteration: 2, 4, 6, 8
- Since both threads execute independently, the exact order of odd and even output is not guaranteed.
class TaskOddEven extends Thread {
private int number;
private String name;
public TaskOddEven(String name, int number) {
this.name = name;
this.number = number;
}
@Override
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println(name + number);
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
Difference Between start() and run() in Java
The main difference is that start() creates a new thread of execution, whereas calling run() directly executes like a normal method on the current thread.
start() Method :
Java starts a new thread, and that new thread executes the run() method.
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Running: " + Thread.currentThread().getName());
}
}
public class Test {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
run() Method :
Java does not start a new thread. The run() method executes like a regular method on the current thread.
MyThread t1 = new MyThread();
t1.run();