我有一个任务,我想每毫秒更新一些内容(某种计算)。现在这就是我正在做的事情,延迟 1 毫秒。-
int countertest =0;
myRunnable = new Runnable() {
@Override
public void run() {
countertest++;
System.out.println("----counter----->"+countertest);
myHandler.postDelayed(myRunnable, 1); //runs every 1 millisecond
}
};
我通过单击按钮启动 myHandler
并在 1 秒后停止它 (removeCallbacksAndMessages(null)
)。现在,myHandler
应该在一秒钟内运行它 1000 次。但它有时会运行 110 次,有时会运行 119 次……有时会运行一些随机数。不知道为什么它没有在 1 秒内运行 1000 次。任何人都可以详细说明一下吗?
我现在应该怎么做才能在 1 秒内执行 1000 次?举个例子,如果我想在一秒内显示从 0000 到 1000 的文本,或者在 1 秒内精确打印 0-1000,既不超过 1 秒也不少于 1 秒。 反对者请。请在下面发表评论,以便我知道我错在哪里。谢谢。
用于上述测试的设备 - Samsung S9。
最佳答案
如上所述here ,根本无法保证“您的”系统的毫秒精度:
Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
关于java - 处理程序未在 1 秒内运行 1000 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51383626/