Question: How long does your thread have slept after Thread .sleep (500)?

xiaoxiao2021-03-05  22

When we inherit the Canvas class in J2ME, we generally reach the RunNable interface, realize multi-threaded effect, personal thinking of this thread is just a timer, you can use a Timer or use an Inner Class. Implement this function, there is no more discussion on this.

Our run () This function is generally implemented such a function, and the timing processing game logic GameLogic () and redraw screen Paint (). Note that the timing here is the focus of this article, if the interval time of the game logic and the heavy picture screen is not fixed. It must destroy the authenticity of the gameplay and the game screen.

Ok, let's take a look at the general processing method ()

Public void run () {

While (true) {

Gamelogic (); // handle game logic

Repaint (); // Call the Paint () redraw screen

Thread.sleep (500); // Thread SLEEP0.5 seconds

}

}

It seems that every time the interval is 0.5 seconds. But have you ever thought that if a complex logic game Gamelogic (), and Paint () actually requires a lot of time to handle, and for a complex logic game, each processing is different, possibly The first Gamelogic () PAINT () time is 0.1 seconds, and it may be 0.01 seconds. This does not cause unfairness of the interval time. So we must calculate the calculation time of Gamelogic (), and Paint (), just like it is below.

Public void run () {

Time0 = system.currenttimemillis ();

While (true) {

Time1 = system.currenttimemillis ();

TimePassed = TIME1 - TIME0;

Time0 = TIME1;

Gamelogic (); // handle game logic

Repaint ();

Time1 = system.currenttimemillis ();

IF (Time1 - Time0

Try {

Thread.sleep (Run_Rate - (Time1 - Time0));

}

Catch (InterruptedException E) {

}

}

}

}

转载请注明原文地址:https://www.9cbs.com/read-38101.html

New Post(0)