我写了一个使用System.nanotime的安卓定时器应用。问题是它给了我预测不足的结果和负数。在摄影机的每个帧上更新redVal、blueVal和greenVal。
结果
504455566
-95947265
9063721
61035
-99487305
-98937988
12664795
-75317382代码
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();
}
}发布于 2015-09-10 06:16:31
您正在尝试输出一个时间差,该时间差依赖于在不同线程中设置的值,而不需要任何同步。这几乎总是以错误的值结束:
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);
}您不能简单地依赖于线程按照您编写的顺序执行的顺序--而且绝对不能在循环中执行。我不能从你的问题中理解你在尝试计时,但是带回家的规则是,当你有多个线程时,你可以在不使用某种形式的同步的情况下执行的顺序。
https://stackoverflow.com/questions/32489283
复制相似问题