简体   繁体   English

Java Handler Post Delayed任务计时器不正确

[英]Java Handler Post Delayed task is not accurate timer

I have created two Handlers, which each have Runnable Tasks which run in a loop through: 我创建了两个处理程序,每个处理程序都有可运行的任务,这些任务通过以下循环运行:

// do it again 1 hundeth of a sec later
QuestionHandler.postDelayed(QuestionHandlerTask, 10); 

And through: 并通过:

// and do it again 1 sec later
GameHandler.postDelayed(GameHandlerTask, 1000); 

Both the tasks start at 10 and count downwards and their results are displayed in labels. 这两个任务都从10开始并向下计数,其结果显示在标签中。 The reason i have used 2 handler's is because i want 1 timer to count down by milleseconds and 1 to count down by seconds. 我使用2个处理程序的原因是因为我希望1个计时器以毫秒为单位倒数,而1个计时器以秒为单位倒数。

However, the GameHandlerTask that runs once per second runs significantly faster than the other. 但是,每秒运行一次的GameHandlerTask的运行速度明显快于另一个。 By the time it reaches 1 the QuestionHandlerTask is still at 4 seconds: 到1时,QuestionHandlerTask仍处于4秒:

在此处输入图片说明

Is this a commonly known problem or have i done something seriously wrong? 这是一个众所周知的问题,还是我做错了什么严重的事情? Is there some way i can make it so my timers run at the same speed? 有什么办法可以使计时器以相同的速度运行? Is there other methods that i can use that would be better in this circumstance (where i want precise timing)? 在这种情况下(我需要精确的计时),还有其他可以使用的更好的方法吗?

This is because the screen cannot refresh 100 times per second, which is what is happening with the 10 millisecond timer. 这是因为屏幕无法每秒刷新100次,而10毫秒计时器正在发生这种情况。 So the screen tries to show every single value that you told it to show, but can only do so at its maximum refresh rate. 因此,屏幕尝试显示您告诉它显示的每个值,但只能以其最大刷新率进行显示。

It is not the timer that is slow, it is the screen that can't keep up with the timer. 不是计时器变慢,而是屏幕无法跟上计时器。

To solve this, try to calculate how much does the number need to go down by in 40 milliseconds, and you start a timer of 40ms. 要解决此问题,请尝试计算该数字在40毫秒内需要减少多少,然后启动40ms的计时器。 This will update the screen 25 times a second, which the screen should be able to handle. 这将每秒更新屏幕25次,该屏幕应该能够处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM