problem in understanding the setRunning (boolean run) method
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){
}
}
}
}
my confusion is that i have initialize-->private boolean running = false; after that i assigned-->
public void setRunning(boolean run)
{
running = run;
}
so what "running" realy holds, what is the vale 开发者_JS百科of "run"?sombody plz explain setRunning(boolean run) method.
run
will hold whatever you pass as the argument to the setRunning()
method. It will be either true
or false
.
From the looks of the code, it appears to control re-drawing the Canvas
. As long as running
is true
(by means of calling setRunning(true)
on the Thread
), it will re-draw the Canvas
every 100 ms (or 10 frames per second).
EDIT
You should declarerunning
using the volatile
modifier in order for proper synchronization to occur. If you do not include the modifier, and you call setRunning()
from another thread, the "expected" result is not guaranteed.
See here.
精彩评论