java - NotifyAll 不工作

标签 java multithreading notify

此代码从两个不同的线程打印偶数/奇数。在这里,我的程序卡在 wait() 中,无法使用 notifyAll() 唤醒 sleep 线程。

想知道为什么notifyAll无法唤醒所有 hibernate 的线程? 需要知道我在这里做错了什么。

class EvenOddThread {
  public static void main (String [] args) {
  Runnable runnEven = new ThreadPrint (true, 10);
  Runnable runnOdd = new ThreadPrint (false, 10);

  Thread t1 = new Thread (runnEven);
  Thread t2 = new Thread (runnOdd);

  t1.start ();
  t2.start ();
  }
}

class ThreadPrint implements Runnable {
  private boolean isEvenPrint = false;
  private int maxPoint = 0;
  ThreadPrint (boolean isEven, int max) {
    isEvenPrint = isEven;
    maxPoint = max;
  }

  @Override
  public void run () {
    Print p = new Print();
    if (isEvenPrint)
      p.printEven(maxPoint);
    else
      p.printOdd(maxPoint);
  }
}

class Print {


  public synchronized void printEven (int maxPoint) {
    int even = 0;
    while (even <= maxPoint) {
      System.out.println(even);
      even = even + 2;
      try {
      wait();
    }
    catch (Exception e) {
      System.out.println(e);
    }

    notifyAll();
    }
  }

  public synchronized void printOdd (int maxPoint) {
    int odd = 1;
    while (odd <= maxPoint) {


    System.out.println(odd);
    odd = odd + 2;
    try {
      wait();
    }
    catch (Exception e) {
      System.out.println(e);
    }

      notifyAll();
    }
  }
}

谢谢, 希瓦姆

最佳答案

两个线程在打印第一个数字后都进入wait。由于两个线程都已暂停,因此两个线程都无法唤醒另一个。

为了让一对线程以这种方式交替,您可以有单独的条件来控制每个线程的进度。每个线程在完成自己的工作单元后会解除对另一个线程的阻塞。这可以通过 Semaphore 来完成, CyclicBarrier , 或 Phaser .

关于java - NotifyAll 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51678241/

相关文章:

java - Spring mvc : java. lang.AbstractMethodError

java - Hibernate createNativeQuery 使用 IN 子句

c# - 听取使用 IEnumerable<T> 时用于 BlockingCollection 的 Queue.Peek() 的模拟

c++ - C++中成员修改的事件/通知

java - Eclipse 4.5 (Mars) 格式 : No white space between generic extends and implements in Class declaration

java - 我们如何在 Node 类中创建 "Node"类型字段?

objective-c - 应该如何更改此代码才能正常工作?

c++ - Qt moveToThread 和数据竞争

php - 当 MySql 数据库条目更改时发送通知

java - 创建一个类以从 Java 中的另一个类调用其 notify()