有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用运行时在一秒钟内退出循环?

如何使用Runtime在一秒钟内退出循环? 我想用这个密码

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


       }
}

共 (5) 个答案

  1. # 1 楼答案

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

    好的,要做到这一点,你需要记录开始时间,然后将其与当前时间进行比较

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

    上面的代码可能会花费更多的时间来完成你想做的事情

  3. # 3 楼答案

    long startTime = System.currentTimeMillis();
    
    while((System.currentTimeMillis()-startTime)<=1000){
         str=str + "a"; 
    }
    
  4. # 4 楼答案

    我认为,如果你真的不需要使用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();
        }
    }
    
  5. # 5 楼答案

    在while循环中编写代码。它将在1秒后退出循环

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