[英]System.nanotime giving negative numbers
我寫了一個使用System.nanotime的android定時器應用程序。 問題是它給了我低估的結果以及負數。 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();
}
}
您試圖輸出時差,該時差依賴於在不同線程中設置的值,而沒有任何同步。 這幾乎總是會導致錯誤的值:
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);
}
您根本不能依賴於按照對它們進行編碼的順序來執行線程的順序-絕對不是循環的。 從您的問題中我無法理解您要嘗試計時的時間,但扎根的規則是,只要您有多個線程,就永遠不能依靠執行順序而不使用某種形式的同步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.