Question: Thread. Sleep (500) How long has your thread been asleep?

Source: Internet
Author: User
Tags sleep thread time interval
Problem
When we inherit the canvas class in J2ME, we will realize the runnable interface and realize the effect of multithreading. Personally think that actually this thread is just a timer function, can be used a timer or a inner class to achieve this function, There is not much discussion about this here.

Our run () function is generally to implement this function, timed to handle game logic gamelogic () and redraw the screen paint (). Note that the timing here is the focus of this article, if the game logic and redraw screen time interval is not fixed. Must destroy the gameplay and the authenticity of the game screen.

Okay, let's take a look at the general approach ()

public void Run () {

while (true) {

Gamelogic ()//Handling game logic

Repaint ()//Call Paint () repaint screen

Thread.Sleep (500);/thread sleep0.5 seconds

}

}

It looks like the interval is 0.5 seconds each time. But have you ever thought that if a complex logic game gamelogic (), and paint () actually also takes a lot of time to deal with, and for a complex logic game, the length of time for each processing is not the same, may be the first time gamelogic () +paint () The time is 0.1 seconds and the next one may be 0.01 seconds. This does not cause the interval time is not fixed. So we have to calculate the Gamelogic (), and the paint () of the computation time, just like the following.

public void Run () {

TIME0 = System.currenttimemillis ();

while (true) {

time1 = System.currenttimemillis ();

timepassed = TIME1-TIME0;

TIME0 = time1;

Gamelogic ()//Handling game logic

Repaint ();

time1 = System.currenttimemillis ();

if (TIME1-TIME0 < run_rate) {

try {

Thread.Sleep (Run_rate-(TIME1-TIME0));

}

catch (Interruptedexception e) {

}

}

}

}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.