我正在做一个俄罗斯方块程序,想用2个线程同步来控制暂停和继续游戏,但做出来有问题,希望懂的人看下,帮下忙
这是那个俄罗斯方块程序,想加个暂停和继续的功能, http://download.csdn.net/source/3259482
本来我想这么弄,但好像出问题了。。
private class ShapeDriver implements Runnable
{ @Override
public void run()
{
// TODO Auto-generated method stub
synchronized(Shape.this)
{
while(listener.isShapeMoveDownable(Shape.this))
{
if(isPause == true)
{
try
{
Shape.this.wait();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
moveDown();
listener.shapeMoveDown(Shape.this);
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public class NotifyDriver implements Runnable
{ @Override
public void run()
{
synchronized(Shape.this)
{
while(true)
{
System.out.println("11111111111111111111111111111111111111111111111Pause");
if(isPause == false)
{
Shape.this.notify();
}
else
{
try
{
Shape.this.wait();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public void setPause()
{
isPause = true;
}
public void setContinue()
{
isPause = false;
}
这是那个俄罗斯方块程序,想加个暂停和继续的功能, http://download.csdn.net/source/3259482
本来我想这么弄,但好像出问题了。。
private class ShapeDriver implements Runnable
{ @Override
public void run()
{
// TODO Auto-generated method stub
synchronized(Shape.this)
{
while(listener.isShapeMoveDownable(Shape.this))
{
if(isPause == true)
{
try
{
Shape.this.wait();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
moveDown();
listener.shapeMoveDown(Shape.this);
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public class NotifyDriver implements Runnable
{ @Override
public void run()
{
synchronized(Shape.this)
{
while(true)
{
System.out.println("11111111111111111111111111111111111111111111111Pause");
if(isPause == false)
{
Shape.this.notify();
}
else
{
try
{
Shape.this.wait();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public void setPause()
{
isPause = true;
}
public void setContinue()
{
isPause = false;
}
如果是的话可以直接用javax.swing.Timer,这个类已经封装好了,可以设置时间间隔,暂停,继续等。如果用线程的话,设标志位就可以了class ShapeDriver implements Runnable{
private boolean flag;
public void pause(){
flag=flase;
} public void start(){
flag=true;
} public void run(){
while(flag){
//操作
}
Thread.currentThread().sleep(TIME_TO_SLEEP);
}
}
{ @Override
public void run()
{
// TODO Auto-generated method stub
while(!isPause)
{
//操作
if(listener.isShapeMoveDownable(Shape.this))
{
moveDown();
listener.shapeMoveDown(Shape.this);
}
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}