I got asked this question recently in an interview.
Write a program with two threads (A and B), where A prints 1 , B prints 2 and so on until 50 is r
May be this is still relevant:
public class MyRunnable implements Runnable {
public static int counter = 0;
public static int turn = 0;
public static Object lock = new Object();
@Override
public void run() {
while (counter < 50) {
synchronized (lock) {
if (turn == 0) {
System.out.println(counter + " from thread "
+ Thread.currentThread().getName());
turn = 1;
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
turn = 0;
lock.notify();
}
}
}
}
}
and then the main function
public static void main(String[] args) {
Thread threadA = new Thread(new MyRunnable());
Thread threadB = new Thread(new MyRunnable ());
threadA.start();
threadB.start();
}