0

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


       }
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64

5 Answers5

1
long startTime = System.currentTimeMillis();

while((System.currentTimeMillis()-startTime)<=1000){
     str=str + "a"; 
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

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

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0
 long startTime = System.currentTimeMillis();
 while((System.currentTimeMillis()-startTime)<1000){
// Your task goes here
}
Subir Kumar Sao
  • 8,171
  • 3
  • 26
  • 47
  • I want to count how many string can I add in one second like while (somthing < one second) { str=str + "a"; } System.out.println(str); – user3222289 Mar 07 '14 at 08:07
0

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
}
kaushik parmar
  • 805
  • 6
  • 19
0

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();
    }
}
Baniares
  • 525
  • 1
  • 3
  • 9