I am working on below interview question:

> 
> There are three threads in a process. The first thread prints 1 1 1
>  ..., the second one prints 2 2 2 ..., and the third one prints 3 3 3
>  ... endlessly. How do you schedule these three threads in order to
>  print 1 2 3 1 2 3 ...
> 
> 
> 

I came up with below code which prints `1 2 1 2 1 2` using two threads but I am not able to figure out the condition on how to print number `3` here from third thread.

```
public class PrintOneTwoThree {
  private static boolean isFirst = true;
  private static final Object lock = new Object();

  public static void main(String[] args) {
    // first thread
    new Thread(() -> {
      try {
        synchronized (lock) {
          for (;;) {
            while (!isFirst) {
              lock.wait();
            }
            System.out.print("1 ");
            isFirst = false;
            lock.notify();
          }
        }
      } catch (InterruptedException ignored) {
      }
    }).start();

    // second thread
    new Thread(() -> {
      try {
        synchronized (lock) {
          for (;;) {
            while (isFirst) {
              lock.wait();
            }
            System.out.print("2 ");
            isFirst = true;
            lock.notify();
          }
        }
      } catch (InterruptedException ignored) {
      }
    }).start();
  }
}

```

How to solve this kind of problem efficiently?