Print Even and Odd Numbers using two threads in java

Frequently asked multi-threading interview question in java is printing odd numbers by one thread and even numbers by another thread in ascending order. Interviewer wants to check if you are able to implement thread communication properly.


package thread;

public class EvenOddByThreads {

public static void main(String[] args) {
Object obj = new Object();
Thread odd = new Thread(new EvenOddThread(obj, 1));
Thread even = new Thread(new EvenOddThread(obj, 2));

odd.start();
even.start();
}

}

class EvenOddThread implements Runnable {

private Object lock;
private int start;

public EvenOddThread(Object lock, int start){
this.lock = lock;
this.start = start;
}
@Override
public void run() {
synchronized (lock) {
for (int i=start; i<=20; i+=2) {
try {
System.out.println(i);
lock.notify();
lock.wait();
} catch (Exception e) {

}
}
}
}
}

Comments

Popular posts from this blog

JMeter – Working with JSON

Hyperlocal Startups Creating a Better Living

Existence: Absolute & Relative