I have written the following piece of code to have two threads printing odd and even numbers alternatively. I know this is a common question but I wanted to get this reviewed and understand if it is right or wrong. If wrong, can this be tweaked slightly to get desired result or the approach itself is wrong. Thanks for help.
public class ThreadTest implements Runnable{
private static int counter = 1;
private static final Object lock = new Object();
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(new ThreadTest(), "arunabh");
t1.start();
Thread t2 = new Thread(new ThreadTest(), "hejib");
t2.start();
}
@Override
public void run() {
while (counter<=100) {
synchronized (lock) {
if (counter % 2 == 0) {
System.out.println(counter +" Written By even Thread-"+ Thread.currentThread().getName());
counter++;
try {
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (counter % 2 == 1) {
System.out.println(counter +" Written By odd Thread-"+ Thread.currentThread().getName());
counter++;
try {
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}