我有这个代码:
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();
}
我有两个线程假设由相同的代码运行,一个应该twin.wait()
在方法中运行,另一个应该在方法run()
中调用,但问题是当有一个 for 它不调用时,当我删除因为它调用它,为什么会这样,我该如何解决它?NotifyAll()
moveStep()
NotifyAll()