gpt4 book ai didi

java - Android - 是否可以每毫秒至少运行一次线程更新?

转载 作者:行者123 更新时间:2023-12-01 23:31:10 25 4
gpt4 key购买 nike

我想编写一个Android应用程序(确切地说是一个游戏),它需要在指定的时间执行某些操作。这些更新的精度不应低于1ms。这可能吗?

我尝试运行一个线程并使用 System.nanoTime() 测量更新之间的时间。结果,有数百次更新之间的时间等于或长于 1 毫秒。

我能否以某种方式达到一定的精度,以确保每 1 毫秒至少执行一个循环?

这是我用于测试的代码:

public class MyThread extends Thread
{
private boolean running = false;
public void setRunning(boolean running)
{
this.running = running;
}

public MyThread()
{
this.setPriority(MAX_PRIORITY);
}

@Override
public void run()
{
long currentTimeNano = 0;
long lastFrameTimeNano = 0;
long nanoFrameDelay = 0;
int longDelays = 0; //Number of delays >= 1ms

while(running)
{
currentTimeNano = System.nanoTime();

//Measure delay between updates in ns
nanoFrameDelay = currentTimeNano - lastFrameTimeNano;

if(nanoFrameDelay >= 1000000)
longDelays++;

lastFrameTimeNano = currentTimeNano;
}
}
}

提前谢谢您!

最佳答案

使用常规 java、硬件和 Thread.sleep() 之类的东西不可能达到 1ms 的精度。

要达到 1 毫秒的精度,您需要一个实时平台。

取自 http://www.onjava.com/pub/a/onjava/2006/05/10/real-time-java-introduction.html

According to Greg Bollella, a distinguished engineer at Sun Microsystems and one of the authors of the real-time Java specification, real time means "the ability to reliably and predictably reason about and control the temporal behavior of program logic." Real time does not mean "fast," as many developers might think; it means predictable and reliable when a reaction to real-world events is required. The real-time computer will always respond before a particular deadline that you've assigned it. Depending on how you set your deadlines, numerous systems could be called real-time.

请参阅此讨论: Java - alternative to thread.sleep

更具体地说,本文讨论了部署实时应用程序的可能性: http://www.embedded.com/electronics-blogs/cole-bin/4372870/Real-time-Android--real-possibility--really-really-hard-to-do---or-just-plain-impossible--

或者这个:http://www.ittc.ku.edu/~niehaus/classes/753-f10/notes/sarvesh_android.pdf

基本上,我认为您对于股票、市场应用程序不走运。如果这适用于您的公司,您可以尝试对每个设备进行 root 并使用实时内核,但您正在冒险进入大多数未知的领域。即使使用该路线,也无法保证 1 毫秒的精度。

但是......

<小时/>

编辑:看来您的情况不需要 1 毫秒的精度。碰巧我的论文是基于视听线索和同时性感知。

长话短说,对于 2 个音频信号(1 个来自左耳,1 个来自右耳),只有当两个信号间隔超过 10ms 时,才能判断两个脉冲输入是否有延迟。大多数人在 50 毫秒时难以区分事件的顺序。

对于视力来说,正常的眼睛只能在大约 150Hz 的频率下工作,因此任何小于 7ms 的延迟都没有什么区别。我见过的最佳刷新率约为 200Hz,即 5 毫秒延迟。然而,这仅适用于检测明亮的闪光,而不是确定两个事件并发的情况。对于类似于您尝试做的事情,我能够安全地获得高达 60 毫秒的延迟,而在视听同步性方面没有任何重大的明显不匹配。您的用例可能需要更少的东西。 ~50ms 似乎是一个神奇的数字。对于这种类型的准确性, sleep() 应该足够了。您的案例不需要实时系统。

关于java - Android - 是否可以每毫秒至少运行一次线程更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19251484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com