2017-04-16 72 views
-1

我需要计算两次之间的时间。当它在Thread中调用时,System.currentTimeMillis()每次返回相同的值。 我的代码是:System.currentTimeMillis()返回相同的时间戳

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // Other codes.. 
    start_sec = Math.round(System.currentTimeMillis()/1000); 
    fin = false; 
    runThread(); 
    // Other codes.. 
} 

private void runThread() { 
    new Thread() { 
     public void run() { 
      while (i++ < 61) { 
       if (!running) return; 
       try { 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          if(!fin){ 
           int len = Math.round(System.currentTimeMillis()/1000) - start_sec; 
           Log.d("current time: ",String.valueOf( Math.round(System.currentTimeMillis()/1000))); 
           Log.d("difference is: ", String.valueOf(len)); 
           if(len < 0 && len > 58){ 
            fin=true; 
           } 
           timerec.getLayoutParams().width = metrics.widthPixels *(60- len)/60; 
           timerec.requestLayout(); 
          } 
          else{ 
           end_game(); 
           running= true; 
          } 
         } 
        }); 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    }.start(); 
} 

下面是日志:

... 
D/current time:: 1492337024 
D/difference is:: 0 
D/current time:: 1492337024 
D/difference is:: 0 
.... 

它returs相同的 “时间”。解决办法是什么?

回答

0

Math.round()导致的问题。

long len = System.currentTimeMillis()/1000 - start_sec; 
Log.d("current time: ",String.valueOf(System.currentTimeMillis()/1000)); 
Log.d("difference is: ", String.valueOf(len)); 

此代码altought分。

0

需要时间。不要把它除以1000.时间差是秒的几分之一。这就是为什么当你四舍五入时它显示的时间相同。

0

while循环中两个循环之间的差异远小于一秒,并且当您以秒为单位计算差值(您将当前毫秒分为1000)时,它会使秒数相同,差值为0秒。

尝试以毫秒为单位打印差异(不分割)。

0

试试这个:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // Other codes.. 
    start_sec = System.currentTimeMillis(); 
    fin = false; 
    runThread(); 
    // Other codes.. 
} 

private void runThread() { 
    new Thread() { 
     public void run() { 
      while (i++ < 61) { 
       if (!running) return; 
       try { 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          if(!fin){ 
           int len = System.currentTimeMillis() - start_sec; 
           Log.d("current time: ",String.valueOf( System.currentTimeMillis())); 
           Log.d("difference is: ", String.valueOf(len)); 
           if(len < 0 && len > 58){ 
            fin=true; 
           } 
           timerec.getLayoutParams().width = metrics.widthPixels *(60- len)/60; 
           timerec.requestLayout(); 
          } 
          else{ 
           end_game(); 
           running= true; 
          } 
         } 
        }); 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    }.start(); 
}