0

I'm learning Java's multithreading and now trying following:

I'd like to have two threads, thread A prints odd numbers only, thread B prints even number only.

When thread A finishs output a number, it tells B: "it is your turn to print", vice versa. In C++ I use semaphore for such things, but I don't know how to do it in Java.

Here is my code:

class printer {
  int i;
  void say() {
    System.out.println(i++);
  }
}

class p1 extends printer implements Runnable {
  public void run() {
    while (true) {
      //waitP2();
      say();
      //tellP2();
      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {}
    }
  }
}

class p2 extends printer implements Runnable {
  public void run() {
    while (true) {
      //waitP1();
      say();
      //tellP1();
      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {}
    }
  }
}

public class a {
  public static void main(String[] args) {
    Thread t1 = new Thread(new p1());
    Thread t2 = new Thread(new p2());
    t1.start(); t2.start();
    try {
      t1.join(); t2.join();
    } catch (InterruptedException e) {}
  }
}
Deqing
  • 14,098
  • 15
  • 84
  • 131
  • 1
    Java has a `Semaphore` class. You could attempt to do the same thing. – Sotirios Delimanolis Oct 01 '14 at 14:23
  • 1
    This is a [very common](http://stackoverflow.com/questions/16689449/printing-even-and-odd-using-two-threads-in-java) exercise. See [here](http://stackoverflow.com/questions/18799591/print-natural-sequence-with-help-of-2-threads1-is-printing-even-and-2nd-is-pri). Another with [semaphores](http://stackoverflow.com/questions/22976412/how-to-make-sure-two-threads-printing-even-odd-numbers-maintain-even-first-then). – Sotirios Delimanolis Oct 01 '14 at 14:24
  • Thanks, good to know I can use similar Semaphore in Java. – Deqing Oct 02 '14 at 01:26

0 Answers0