This was a question asked in one of my interviews:
You have 2 different classes (which implement Runnable) say EvenThread and OddThread. As the name implies, EvenThread prints only even numbers, and an odd stream prints only odd numbers, consider the range 0-100.
class EvenThread implements Runnable { @Override public void run() { for (int i = 0; i <= 10; i += 2) { System.out.println(i); } } } class OddThread implements Runnable { @Override public void run() { for (int i = 1; i < 10; i += 2) { System.out.println(i); } } } public class EvenOdd { public static void main(String args[]) { Thread tEven = new Thread(new EvenThread()); Thread tOdd = new Thread(new OddThread()); tEven.start(); tOdd.start(); } }
Now we need to use the mechanism so that the numbers are printed sequentially (i.e. 0, 1, 2, 3, 4, .... etc.).
I saw a lot of similar questions in Stack Overflow, but they only have one class for printing numbers and it uses 2 synchronized methods.
Can any of the experts suggest?
source share