How to print even and odd numbers using threads in java

Now a day's, a common question asked in interviews are threads. In this post we are going to learn how to implement two thread which is usedto display odd and even numbers.

In the following program, thread 1 prints even numbers and thread 2 prints odd numbers

SOURCE : EvenOddPrinter.java

package com.becbe.threads;

public class EvenOddPrinter implements Runnable {

boolean isEven = false;
Object lock;

public EvenOddPrinter( boolean isEven, Object lock) {
this.isEven = isEven;
this.lock = lock;
}

@Override
public void run() {
System.out.println("Inside Run");
if(isEven) {
printEven();
} else {
printOdd();
}

}

private void printOdd() {
synchronized (lock) {
for (int i = 1; i < 100;) {
lock.notify();
i = i + 2;
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.notify();
System.out.println( i );
}
}
}


private void printEven() {
synchronized (lock) {
lock.notify();
for (int i = 0; i < 100;) {
i = i + 2;
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.notify();
System.out.println( i );
}
}

}

public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(new EvenOddPrinter(true, lock));
Thread t2 = new Thread(new EvenOddPrinter(false, lock));
t1.start();
t2.start();
}

}









Thulasiram P

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Thulasiram P

Follow Me @Google+





SHARE

    Blogger Comment
    Facebook Comment

1 comments :

  1. we can use atomicity feature of java for this kind of questions

    ReplyDelete