[Java] Not fast but simple - BlockingQueue
There are so many solutions with locks, so I wanted to solve them in a different way. \n\n - no explicit locking\n - no atomic class\n\nI believe that code that
There are so many solutions with locks, so I wanted to solve them in a different way. \n\n - no explicit locking\n - no atomic class\n\nI believe that code that uses locks or atomic classes directly is prone to bugs.\nCode is simple.\n\n- even/odd method just consumes channel(queue)\'s element. If given the value is stop signal, just stop. Otherwise, just print and send `0` to the channel for zero.\n- zero method also just consumes(except some init work) value from queue with produce values to each channel(even, odd). If internal counter reaches to n, it stops produce/consume and send stop signal to each channel.\n\n\n```java\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.function.IntConsumer;\n\nclass ZeroEvenOdd {\n  private static final int STOP_SIGNAL = -1;\n\n  private final int n;\n  private final BlockingQueue<Integer> channelForZero = new ArrayBlockingQueue<>(1);\n  private final BlockingQueue<Integer> channelForOdd = new ArrayBlockingQueue<>(1);\n  private final BlockingQueue<Integer> channelForEven = new ArrayBlockingQueue<>(1);\n\n  public ZeroEvenOdd(final int n) {\n    this.n = n;\n  }\n\n  public void zero(final IntConsumer printNumber) throws InterruptedException {\n    if (n < 0) {\n      return;\n    }\n    int counter = 1;\n    channelForZero.offer(0);\n\n    while (counter <= n) {\n      printNumber.accept(channelForZero.take());\n      if (counter % 2 == 0) {\n        channelForEven.offer(counter);\n      } else {\n        channelForOdd.offer(counter);\n      }\n      counter++;\n    }\n    channelForZero.take();\n    channelForOdd.offer(STOP_SIGNAL);\n    channelForEven.offer(STOP_SIGNAL);\n  }\n\n  public void even(final IntConsumer printNumber) throws InterruptedException {\n    while (true) {\n      int given = channelForEven.take();\n      if (given == STOP_SIGNAL) {\n        break;\n      }\n\n      printNumber.accept(given);\n      channelForZero.offer(0);\n    }\n  }\n\n  public void odd(final IntConsumer printNumber) throws InterruptedException {\n    while (true) {\n      int given = channelForOdd.take();\n      if (given == STOP_SIGNAL) {\n        break;\n      }\n\n      printNumber.accept(given);\n      channelForZero.offer(0);\n    }\n  }\n}\n\n```
[]