首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >System.nanotime给出负数

System.nanotime给出负数
EN

Stack Overflow用户
提问于 2015-09-10 05:15:54
回答 1查看 451关注 0票数 1

我写了一个使用System.nanotime的安卓定时器应用。问题是它给了我预测不足的结果和负数。在摄影机的每个帧上更新redVal、blueVal和greenVal。

结果

代码语言:javascript
复制
504455566
-95947265
9063721
61035
-99487305
-98937988
12664795
-75317382

代码

代码语言:javascript
复制
        for (testAmount = 0; testAmount < 80; testAmount++) {
            runOnUiThread(new Runnable() {
                public void run() {
                    lagSquare.setBackgroundColor(Color.rgb(255, 255, 255));
                    lagStartTime = System.nanoTime(); //start lagTimer start
                }
            });
            while (redVal <= 100.0 && blueVal <= 100.0 && greenVal <= 100.0) {
                x=0;
            }
            runOnUiThread(new Runnable() {
                public void run() {
                    lagEndTime = System.nanoTime(); //start lagTimer end
                    lagSquare.setBackgroundColor(Color.rgb(000, 000, 000));//set lagSquare black
                }
            });
            lagTimeResult = (lagEndTime - lagStartTime);
            timeArray[testAmount] = lagTimeResult;
            Log.i("LTR", String.valueOf(lagTimeResult));
            try {
                Thread.sleep(60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
EN

回答 1

Stack Overflow用户

发布于 2015-09-10 06:16:31

您正在尝试输出一个时间差,该时间差依赖于在不同线程中设置的值,而不需要任何同步。这几乎总是以错误的值结束:

代码语言:javascript
复制
for (testAmount = 0; testAmount < 80; testAmount++) {

            // this will schedule the Runnable to run *sometime* in
            // the future - but not necessarily right now
            runOnUiThread(new Runnable() {
                public void run() {
                    lagStartTime = System.nanoTime(); //start lagTimer start
                }
            });

            // this will also schedule this Runnable to run *sometime* in
            // the future - but not necessarily after the first one
            runOnUiThread(new Runnable() {
                public void run() {
                    lagEndTime = System.nanoTime(); //start lagTimer end
                }
            });

            // this will probably execute first (before either of
            // the other Runnables have completed)
            lagTimeResult = (lagEndTime - lagStartTime);
        }

您不能简单地依赖于线程按照您编写的顺序执行的顺序--而且绝对不能在循环中执行。我不能从你的问题中理解你在尝试计时,但是带回家的规则是,当你有多个线程时,你可以在不使用某种形式的同步的情况下执行的顺序。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32489283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档