我如何使用运行时在一秒钟内从循环中退出?我想使用此代码
public class test {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
long usedMemory = runtime.totalMemory()-runtime.freeMemory();
int mbytes = (int) usedMemory/1000; // Used memory (Mbytes)
String str="a";
while (somthing < one second ) {
}
}
long startTime = System.currentTimeMillis();
while((System.currentTimeMillis()-startTime)<=1000){
str=str + "a";
}
可以做到这一点,您需要记录开始时间,然后将其与当前时间进行比较。
long start = System.currentTimeMillis();
String str="a";
while (true) {
long now = System.currentTimeMillis();
if (now - start > 1000)
break;
// do your stuff
str=str + "a";
}
System.out.println (str);
上面的代码可能会花更多的时间花时间做您想做的事情的时间
long startTime = System.currentTimeMillis();
while((System.currentTimeMillis()-startTime)<1000){
// Your task goes here
}
循环中写入您的代码。它将在1秒后退出循环。
long start = System.currentTimeMillis();
long end = start + 1000; // 1000 ms/sec
while (System.currentTimeMillis() < end)
{
// Write your code here
}
我认为,如果您真的不需要使用运行时,您可以使用类似的东西。
public class test {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long currentTime = System.currentTimeMillis();
long usedMemory = runtime.totalMemory()-runtime.freeMemory();
int mbytes = (int) usedMemory/1000; // Used memory (Mbytes)
String str="a";
while (currentTime-startTime<1000) {
currentTime = System.currentTimeMillis();
}
}