Programming





Write a program to Print Even and Odd Numbers Using 2 Threads

Write a program to Print Even and Odd Numbers Using 2 Threads


by Administrator | 25-Mar-2020
Java

Tags:  Multithreading  Core Java  Program

Share: 


Program
public class MultipleThreadingOddEven {
    int count = 1;
    int MAX = 10;

    public void printOdd() {
        synchronized (this) {
            while (count < MAX) {
                while (count % 2 == 0) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print("Odd: " + count + " \n");
                count++;
                notify();
            }
        }
    }

    public void printEven() {
        synchronized (this) {
            while (count < MAX) {
                while (count % 2 == 1) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print("Even: " + count + " \n");
                count++;
                notify();
            }
        }
    }

    public static void main(String[] args) {
        MultipleThreadingOddEven mt = new MultipleThreadingOddEven();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                mt.printEven();
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                mt.printOdd();
            }
        });
        t1.start();
        t2.start();
    }
}
Output:

Odd: 1 
Even: 2 
Odd: 3 
Even: 4 
Odd: 5 
Even: 6 
Odd: 7 
Even: 8 
Odd: 9 
Even: 10 

Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.