Java Thread - print Odd Even Numbers

This is possible by :  EvenOddPrint [synchronization + wait () + notifyAll () ]+ 2 Threads (odd/even) + Task [ impl runnable having run() deciding when to call what method of EvenOddPrint ]

Task#1 -> Write a EvenOddPrint Class 
- flag to decide when to wait else notify and print
-sync printEven() and printOdd() using wait notifyAll


 public class EvenOddPrint {
    

    boolean flag = false;

    synchronized void printEven(int number) {

        if (flag == false) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:" + number);
        flag = false; //once flag is false the odd() will have to print and wait while flag is true
        notifyAll();
    }

    synchronized void printOdd(int number) {
        if (flag == true) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:" + number);
        flag = true;
        notifyAll();

    }
}



TASK #2 - Write a Task Class implementing Runnable having run () having logic to call which of the above print methods

class Task implements Runnable {

    private int max;
    private EvenOddPrint print;
    private boolean isEvenNumber;

    Task(EvenOddPrint print, int max, boolean isEvenNumber) {
        this.print = print;
        this.max = max;
        this.isEvenNumber = isEvenNumber;
    }

    @Override
    public void run() {

        System.out.println("Run method");
        int number = isEvenNumber == true ? 2 : 1;
        while (number <= max) {
            //LOGIC to call which of the print methods
            if (isEvenNumber) {
                // System.out.println("Even : "+
                // Thread.currentThread().getName());
                print.printEven(number);
            } else {
                // System.out.println("Odd : "+
                // Thread.currentThread().getName());
                print.printOdd(number);
            }
            number += 2;
        }

    }

}



TASK#3 - Test class
which creates Thread > passes Task (max,EvenOddPrint, isEvenflag) > call start() which will call tasks run() and begin execution

public class Test {

    public static void main(String ... args){
        EvenOddPrint print = new EvenOddPrint();
        Thread odd = new Thread(new Task(print, 10,  false));
        Thread even = new Thread(new Task(print, 10, true));
        odd.start();
        even.start();

    }

}

 

0 comments: