java - 我代码中的 Wait() 和 NotifyAll() 在 for 循环中不起作用

标签 java multithreading

我有这个代码:

private int           delay;
private int           x,y,R;
private int           dx=3 , dy=3;
private JLabel    box;
private Ball twin;
boolean isWaiting=false;
private  void  moveStep(){
    Dimension size= box.getSize();
    if (x<=0)
    {
        BounceTest.updateSide(0, BounceTest.getSideValue(0) + 1);
        dx = -dx;
        if(!isWaiting)
            twin.isWaiting=false;
            this.notifyAll();
    }


    if(x+2*R >=size.width){         // Bounce
        synchronized(BounceTest.sides[1])
        {
            BounceTest.updateSide(1, BounceTest.getSideValue(1) + 1);
            dx = -dx;
            this.notifyAll();
        }   
    }
    if (y<=0  ||  y+2*R >=size.height)
        dy = -dy;
    x += dx;
    y += dy;

}
public  synchronized void  run(){
    Color  bg = box.getBackground();
    Graphics  g = box.getGraphics();
    for (int i=0; i<5000; i++){

        draw(g,  Color.blue);                        // draw
        try {
            Thread.sleep(delay);                 // sleep
        } catch(InterruptedException e){}
        if(isWaiting)
        {
            System.out.println("ss1");
            try { 
                synchronized (twin) {
                    twin.wait(); 
                }

                }   catch(InterruptedException e) { }
            System.out.println("ss2");
        }
        draw(g, bg);                                     // delete
        moveStep();

    }
    g.dispose();
}

我有两个线程应该由相同的代码运行,一个应该在 run() 方法中到达 twin.wait() ,另一个应该在 moveStep() 方法中调用 NotifyAll() 但问题是当它没有调用 NotifyAll()当我删除 for it 调用它时,这是为什么以及我该如何修复它?

最佳答案

问题是你正在等待双胞胎(这使得线程在对象双胞胎上 hibernate )并且当你想唤醒那个线程时你正在使用通知“这个”。

您应该使用以下两个选项之一更改您的代码:

选项 1

改变:

this.notifyAll();

twin.notifyAll();

选项 2:

synchronized (twin) {
  twin.wait();
}

synchronized (this) {
  this.wait();
}

关于java - 我代码中的 Wait() 和 NotifyAll() 在 for 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16902360/

相关文章:

java - 为什么当我使用多线程重新绘制时我的小程序会闪烁?

linux - 使用现代操作系统调度程序,手动将进程锁定到特定 CPU/内核是否仍然有意义?

java - 如何在html中呈现特殊字符

Java编译器给出一个奇怪的错误

java - 继承GAME的Api方法

java - 如何在不同线程的回调内通知 ArrayAdapter 中的DataSetChanged? - 安卓

c++ - 如何在macOS中测量线程的执行时间?

java - Java 中有 "local interface"这样的东西吗?

java - 为什么 postgresql 不使用正确的顺序?

java - 如何强制我的线程按顺序运行?