两个线程分别输出奇数和偶数,要求交替输出

答案

private static Object mutex = new Object();

public static void main(String[] args) {
  new Thread(() -> {
    synchronized (mutex) {
      int i = 0;
      while (true) {
        System.out.println(i);
        mutex.notify();
        if (i + 2 == 100) {
          return;
        }
        try {
          mutex.wait();
        } catch (Exception e) {
        }
        i += 2;
      }
    }
  }).start();
  new Thread(() -> {
    synchronized (mutex) {
      int i = 1;
      while (true) {
        System.out.println(i);
        mutex.notify();
        if (i + 2 == 101) {
          return;
        }
        try {
          mutex.wait();
        } catch (Exception e) {
        }
        i += 2;
      }
    }
  }).start();

}

results matching ""

    No results matching ""