我有这个代码:
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/