暂停和恢复正在休眠的线程 Java
Pause and resume threads that are sleeping Java
我有一个线程是 运行 模拟,它正在逻辑层中迭代动态系统的一个步骤,然后重新绘制 GUI 以在屏幕上查看结果。为了让用户查看系统是如何变化的,在每次重绘之间有一个休眠,但我还需要暂停模拟以观察变化,这就是停止重绘和系统迭代,直到用户恢复模拟。
目前看起来是这样的:
simulationThread = new Thread(){
@Override
public void run(){
for(int i=0; i<iterations; i++){
world.iterate();
try{
Thread.sleep(100);
}catch( Exception e ){
e.printStackTrace();
}
view.repaint();
}
}
};
simulationThread.start();
我怎样才能暂停 simulationThread 并能够再次恢复它?,我尝试使用 wait() 方法,但是当线程休眠并调用 wait 时出现问题。我怀疑我应该改变线程等待下一次重绘的方式以完成 pause/resume 任务,但我不确定如何。
class Pauser
{
public:
public synchronized void pause()
{
isPaused = true;
}
public synchronized void resume()
{
isPaused = false;
notifyAll();
}
public synchronized void waitIfPaused()
{
while(isPaused)
{
wait();
}
}
private:
boolean isPaused;
};
使用 .pause()
方法暂停模拟,使用 .resume()
方法恢复,并在可以安全暂停时在线程中使用 .waitIfPaused()
方法。例如,您可以在更改系统参数之前使用.waitIfPaused()
。
我有一个线程是 运行 模拟,它正在逻辑层中迭代动态系统的一个步骤,然后重新绘制 GUI 以在屏幕上查看结果。为了让用户查看系统是如何变化的,在每次重绘之间有一个休眠,但我还需要暂停模拟以观察变化,这就是停止重绘和系统迭代,直到用户恢复模拟。
目前看起来是这样的:
simulationThread = new Thread(){
@Override
public void run(){
for(int i=0; i<iterations; i++){
world.iterate();
try{
Thread.sleep(100);
}catch( Exception e ){
e.printStackTrace();
}
view.repaint();
}
}
};
simulationThread.start();
我怎样才能暂停 simulationThread 并能够再次恢复它?,我尝试使用 wait() 方法,但是当线程休眠并调用 wait 时出现问题。我怀疑我应该改变线程等待下一次重绘的方式以完成 pause/resume 任务,但我不确定如何。
class Pauser
{
public:
public synchronized void pause()
{
isPaused = true;
}
public synchronized void resume()
{
isPaused = false;
notifyAll();
}
public synchronized void waitIfPaused()
{
while(isPaused)
{
wait();
}
}
private:
boolean isPaused;
};
使用 .pause()
方法暂停模拟,使用 .resume()
方法恢复,并在可以安全暂停时在线程中使用 .waitIfPaused()
方法。例如,您可以在更改系统参数之前使用.waitIfPaused()
。