Search code examples
javamultithreadinglockingsynchronizedrunnable

Printing Odd and Even number using 2 threads?


I have tried this code. But after printing 0 , it doesn't print anything. It is blocking due to some lock I think.

public class EvenOdd implements Runnable {
    private Object o = new Object();
    private volatile int i = 0;

    public void run() {
        try {
            System.out.println();
            if ( Thread.currentThread().getName().equals( "Even")) {
                printEven();
            } else {
                printOdd();
            }
        } catch ( Exception ee) {
            ee.printStackTrace();
        }
    }

    private void printEven() throws InterruptedException {
        while ( true) {
            synchronized ( o) {
                while ( this.i % 2 == 0) {
                    o.wait();
                }
                System.out.println( Thread.currentThread().getName() + i);
                i++;
                o.notify();
            }
        }
    }

    private void printOdd() throws InterruptedException {
        while ( true) {
            synchronized ( o) {
                while ( this.i % 2 != 0) {
                    o.wait();
                }
                System.out.println( Thread.currentThread().getName() + i);
                i++;
                o.notify();
            }
        }
    }
}

My TestClass:

EvenOdd x = new EvenOdd();
        new Thread(x,"Even").start();
        new Thread(x,"Odd").start();

Where am I wrong? Thank.

P.S : I know this type of question has been asked many times , but I want to try by my own.


Solution

  • My guesses is you are;

    • using one Runnable but both of then think they are even i.e. they both see the first value of 0
    • printEven has to wait for an odd number ad printOdd has to wait for an even number

    EDIT: After running the code the OP fixed the code, it prints

    0
    1
    

    as expected. It may sometimes print 0 and 0 randomly as the first check for odd/even is not synchronized.