'Generating odd even numbers using 2 threads via wait notify?

I am trying to generate odd even numbers using 2 threads via wait notify. But it is only printing 0.

Could someone please explain why it is so.

Below is my code:

package waitNotify2;

class Odd implements Runnable {

    Object lock;
    volatile Integer ai;

    public Odd(Object lock, Integer ai) {
        super();
        this.lock = lock;
        this.ai = ai;
    }

    @Override
    public void run() {
        synchronized(lock) {
            while(true) {
                while(ai % 2 == 0) {
                    try {
                        lock.wait();
                    } catch(InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(ai + " ");
                ai++;
                lock.notify();
            }
        }
    }

}

class Even implements Runnable {

    Object lock;
    volatile Integer ai;

    public Even(Object lock, Integer ai) {
        super();
        this.lock = lock;
        this.ai = ai;
    }

    @Override
    public void run() {
        synchronized(lock) {
            while(true) {
                while(ai % 2 == 1) {
                    try {
                        lock.wait();
                    } catch(InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(ai + " ");
                ai++;
                lock.notify();
            }
        }
    }

}

public class PrintOddEven2 {

    // Driver Code
    public static void main(String[] args) {
        Object o = new Object();
        Integer i = 0;
        Odd odd = new Odd(o,i);
        Even even = new Even(o,i);
        Thread t1 = new Thread(odd);

        Thread t2 = new Thread(even);
        t1.start();
        t2.start();
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source