我试图在用户单击暂停按钮时暂停弹跳球动画,并在单击恢复时恢复它。问题是当我单击暂停按钮时,它应该将suspendRequested 设置为true,因此它进入if 语句并运行while 语句,这会导致线程等待,从而停止球的动画。然后,当用户单击 resume 时,它应该将其设置回 false ,这会将其从 while 循环中中断并继续动画。这不会发生,那么为什么它没有跳出循环呢?
class BallRunnable implements Runnable
{
private Lock suspendLock = new ReentrantLock();
private Condition suspendCondition = suspendLock.newCondition();
private volatile boolean suspendRequested = false;
private boolean isBouncing = true;
private Ball ball;
private Component component;
public static final int STEPS = 1000;
public static final int DELAY = 100;
/**
* Constructs the runnable.
* @param aBall the ball to bounce
* @param aComponent the component in which the ball bounces
*/
public BallRunnable()
{
}
public BallRunnable(Ball aBall, Component aComponent)
{
ball = aBall;
component = aComponent;
}
public void run()
{
while(isBouncing())
{
try
{
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY);
String name = Thread.currentThread().getName();
System.out.println("Ball is bouncing " + name);
if(suspendRequested)
{
suspendLock.lock();
System.out.println("Locking thread");
try
{
while(suspendRequested)
{
System.out.println("About to await");
suspendCondition.await();
}
}
catch (InterruptedException e)
{
}
finally
{
suspendLock.unlock();
System.out.println("Unlocked " + name);
}
}
}
catch (InterruptedException e)
{
}
}
}
public boolean isBouncing()
{
if(isBouncing)
{
return true;
}
else
{
return false;
}
}
public void setBouncing(boolean b)
{
isBouncing = b;
}
public void requestSuspend()
{
suspendRequested = true;
}
public void requestResume()
{
suspendRequested = false;
suspendLock.lock();
try
{
suspendCondition.signalAll();
}
finally
{
suspendLock.unlock();
}
}
}
在这里,它应该在单击按钮时暂停并恢复线程,但不会将它们从循环中中断。如果使它看起来的布尔值设置为true,然后用户按下暂停将其更改为false,它不应该将其打破循环吗?
class BounceFrame extends JFrame
{
BallRunnable br = new BallRunnable();
private BallComponent comp;
/**
* Constructs the frame with the component for showing the bouncing ball and Start and Close
* buttons
*/
public BounceFrame()
{
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
addBall();
//Don't let user click again
System.out.println("Clicked start");
}
});
addButton(buttonPanel, "Pause", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.out.println("Clicked Paused");
br.setBouncing(false);
System.out.println("Clicked Paused STOP BOUNCinG");
br.requestSuspend();
String name = Thread.currentThread().getName();
System.out.println("Clicked Paused REQUEST SUSPEND " + name);
}
});
addButton(buttonPanel, "Resume", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.out.println("Clicked Resume");
br.setBouncing(true);
br.requestResume();
}
});
add(buttonPanel, BorderLayout.SOUTH);
pack();
}
这是家庭作业,所以我不是在寻找解决方案,但是当单击暂停按钮时,我没有看到关于跳出循环的内容是什么?