public class GameLoopThread extends Thread
{
static final long FPS = 10;
private GameView view;
private boolean running = false;
public GameLoopThread(GameView view)
{
this.view = view;
}
public void setRunning(boolean run)
{
running = run;
}
@Override
public void run()
{
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
while (running)
{
Canvas c = null;
startTime = System.currentTimeMillis();
try
{
c = view.getHolder().lockCanvas();
synchronized (view.getHolder())
{
view.onDraw(c);
}
}
finally
{
if (c != null)
{
view.getHolder().unlockCanvasAndPost(c);
}
}
sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
try
{
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
}
catch (Exception e){
}
}
}
}
我的困惑是 我有初始化 - > private boolean running = false; 之后我分配了 - >
public void setRunning(boolean run)
{
running = run;
}
那么“正在运行”究竟是什么,“run”是什么?sombody plz解释了setRunning(boolean run)方法。
答案 0 :(得分:0)
run
将保存您传递的任何内容作为setRunning()
方法的参数。它将是true
或false
。
从代码的外观来看,它似乎可以控制重新绘制Canvas
。只要running
为true
(通过在setRunning(true)
上调用Thread
),就会每隔100毫秒(或10分钟)重新绘制Canvas
每秒帧数。)
修改强>
您应该使用running
修饰符声明volatile
,以便进行正确的同步。如果您不包含修饰符,并且从另一个线程调用setRunning()
,则无法保证“预期”结果。
请参阅here。
答案 1 :(得分:0)