Java Program to print Even and Odd Numbers Using 2 Threads

By | May 30, 2020
  • In this post, we will learn  How to write a java program to print Even and Odd Numbers Using 2 Threads.
  • In the previous post, we already had seen How to Print numbers in sequence using 3 Threads
  • This problem statement follows a similar logic. is used by both threads to print odd and even numbers

Both threads call method numbersGenerator.printNumbers(result) to generate odd and even numbers in sequence

package com.kkjavatutorials.resource;

* @author KK JavaTutorials
* Each thread call method printNumbers to generate numbers in sequence
public class SequenceGeneratorTask implements Runnable {

private NumbersGenerator numbersGenerator;
private int result;

public SequenceGeneratorTask(NumbersGenerator numbersGenerator, int result) {
this.numbersGenerator = numbersGenerator;
this.result = result;

public void run() {


package com.kkjavatutorials.client;

import com.kkjavatutorials.resource.NumbersGenerator;
import com.kkjavatutorials.resource.SequenceGeneratorTask;

* Java Program to print Even and Odd Numbers Using 2 Threads
* @author KK JavaTutorials
public class SequenceNumberGeneratorTest {

private static final int TOTAL_NUMBER_IN_SEQUENCE = 20;
private static final int TOTAL_NUMBER_OF_THREADS = 2;

public static void main(String[] args) {

NumbersGenerator numbersGenerator = new NumbersGenerator(TOTAL_NUMBER_OF_THREADS, TOTAL_NUMBER_IN_SEQUENCE);

//Created three Threads
Thread t1 = new Thread(new SequenceGeneratorTask(numbersGenerator, 1), “Thread-1”);
Thread t2 = new Thread(new SequenceGeneratorTask(numbersGenerator, 0), “Thread-2”);

//Start all three threads


If you run client program then this will generate below output:

Thread-1 1
Thread-2 2
Thread-1 3
Thread-2 4
Thread-1 5
Thread-2 6
Thread-1 7
Thread-2 8
Thread-1 9
Thread-2 10
Thread-1 11
Thread-2 12
Thread-1 13
Thread-2 14
Thread-1 15
Thread-2 16
Thread-1 17
Thread-2 18
Thread-1 19
Thread-2 20

You May Also Like:

Java Program to Swap two numbers using Bitwise XOR Operator?
How to reverse a number in Java
How to check Armstrong number java program
Java program to find factorial of a number
Java Program to Calculate the Power of a Number
Check whether a number is prime or not

That’s all about Java Program to Print Even and Odd Numbers Using 2 Threads?
If you have any feedback or suggestion please feel free to drop in below comment box. 

Leave a Reply

Your email address will not be published. Required fields are marked *