Code to print even and Odd number using two threads Below I am giving you my code which I wrote to print even number using even thread and odd number using odd thread sequentially.

Could anyone please validate my code whether it is correct way of doing it or not? I am getting correct result, but I just want to make sure whether I am doing it in correct way or not.

public class PrintNumberUsingThread {

    public static void main(String[] args) {
        PrintNumberUsingThread example = new PrintNumberUsingThread();
        PNThread pnThread = example.new PNThread(10);
        new Thread(pnThread).start();
        new Thread(pnThread).start();
    }
    class PNThread implements Runnable {

        private int number = 0;
        private int maxNumber;
        public PNThread(int maxNumber) {
            this.maxNumber = maxNumber;
        }
        @Override
        public void run() {

            while (number &lt;= maxNumber) {
                synchronized (this) {

                    String threadName = Thread.currentThread().getName();
                    if (number &lt;= maxNumber) {

                        boolean even = threadName.contains("0") &amp;&amp; number % 2 == 0;
                        boolean odd = threadName.contains("1") &amp;&amp; number % 2 != 0;
                        if (even || odd) {

                            System.out.println(threadName + "-" + number++);
                            this.notifyAll();
                        } else {
                            try {
                                this.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}
If the only requirement is to have two threads, one printing even numbers and other printing odd numbers, then your solution is unnecessarily complicated. The fact that you share the same data model for both threads forces you to synchronize access to the object making the solution unnecessarily complicated. The assignment did not require numbers being printed in sequence, so the coordination between the threads is unnecessary.

public class Counter implements Runnable {
    private final int start;
    private final int end;
    private final int increment;
    ... add boilerplate constructor ...
    public void run() {
        for (int i = start; i &lt;= end; i += increment) {
            System.out.println(i);
        }
    }
}


Start threads:

new Thread(new Counter(1, 10, 2)).start();
new Thread(new Counter(2, 10, 2)).start();