I'm trying to create two threads OddThread and EvenThread which prints odd number and even number respectively. I've tried to sync those two threads to print natural numbers.
It is working fine but i don't know why it is getting into deadlock after sometime.
My code looks like this:
public class NaturalNoPrint {
public static void main(String[] args) {
Object lock = new Object();
Thread oddThread = new Thread(new OddThread(lock));
Thread evenThread = new Thread(new EvenThread(lock));
oddThread.start();
evenThread.start();
}
}
class OddThread implements Runnable{
private int no=1;
private Object lock;
OddThread(Object lock){
this.lock=lock;
}
public void run(){
while(true){
synchronized(lock){
try {
lock.wait();
System.out.println(no);
no+=2;
lock.notify();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class EvenThread implements Runnable{
private int no=2;
private Object lock;
EvenThread(Object lock){
this.lock=lock;
}
public void run(){
while(true){
synchronized(lock){
try{
lock.notify();
lock.wait();
System.out.println(no);
no+=2;
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
Please help to to identify the cause of deadlock.