loader image

Java program to display odd and even numbers using thread

Write a multi-thread java program for displaying odd numbers and even numbers up to a limit.

import java.util.Scanner;

public class OddEvenThread implements Runnable {

    public static void main(String[] args) {
        int limit;

        // Scanner class object to read input values
        Scanner sc = new Scanner(System.in);

        //read limit from user
        System.out.print("Enter the limit : ");
        limit = sc.nextInt();
        
        // create two threads
        Thread t1 = new Thread(new OddRunnable(limit));
        Thread t2 = new Thread(new EvenRunnable(limit));

        // Start both threads
        t1.start();
        t2.start();
    }

}

class OddRunnable implements Runnable {
    int limit;

    public OddRunnable(int limit) {
        this.limit = limit;
    }

    public void run() {
        for (int even =2;even <= limit;even+=2) {
            System.out.println("Even thread : " + even);
        }
    }
}

class EvenRunnable implements Runnable {
    int limit;

    public EvenRunnable(int limit) {
        this.limit = limit;
    }

    public void run() {
        for (int odd=1;odd <= limit;odd+=2) {
            System.out.println("Odd thread : " + odd);
        }

    }
}

Output

Enter the limit : 10
Odd thread : 1
Odd thread : 3
Odd thread : 5
Odd thread : 7
Odd thread : 9
Even thread : 2
Even thread : 4
Even thread : 6
Even thread : 8
Even thread : 10
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Scroll to Top