asi*_*swt 1 java time loops while-loop
下面的Java方法是指以打印数i由nLoopsPerSecond每秒次seconds秒:
public void test(int nLoopsPerSecond, int seconds) {
double secondsPerLoop = 1.0/(double)nLoopsPerSecond;
long startTime = System.currentTimeMillis();
long currentTime;
int i = 0;
while ((currentTime = System.currentTimeMillis()) < startTime + seconds*1000) {
System.out.println(i++);
while (System.currentTimeMillis() < currentTime + secondsPerLoop*1000);
}
}
Run Code Online (Sandbox Code Playgroud)
通过以下电话:
test(1000,1);
Run Code Online (Sandbox Code Playgroud)
我希望这种方法可以做System.out.println(i++);1000次,但我只有63次.
当我尝试使用此代码查看每个循环实际使用的秒数
public void test(int nLoopsPerSecond, int seconds) {
double secondsPerLoop = 1.0/(double)nLoopsPerSecond;
long startTime = System.currentTimeMillis();
long currentTime;
int i = 0;
while ((currentTime = System.currentTimeMillis()) < startTime + seconds*1000) {
while (System.currentTimeMillis() < currentTime + secondsPerLoop*1000);
System.out.println(System.currentTimeMillis() - currentTime);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望1每个循环打印毫秒,但它打印15或16毫秒.
请提出我的代码中的错误.