此代码从两个不同的线程打印偶数/奇数。在这里,我的程序卡在 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/