Pergunta

how I can exit from a loop in one second using Runtime? I want use this code

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 ) {


       }
}
Foi útil?

Solução

long startTime = System.currentTimeMillis();

while((System.currentTimeMillis()-startTime)<=1000){
     str=str + "a"; 
}

Outras dicas

ok to do this you need to records the start time, and then compare it to the current time as you go.

    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);

The above code will probably spend more time getting the time that doing the stuff you want though

 long startTime = System.currentTimeMillis();
 while((System.currentTimeMillis()-startTime)<1000){
// Your task goes here
}

Write your code in while loop. It will exit the loop after 1 second.

long start = System.currentTimeMillis();
long end = start + 1000; //  1000 ms/sec
while (System.currentTimeMillis() < end)
{
    // Write your code here
}

i think that you can use something like this if you don't really need to use Runtime.

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();
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top