【问题标题】:how I can exit from a loop in one second using Runtime?如何使用运行时在一秒钟内退出循环?
【发布时间】:2014-04-10 06:12:23
【问题描述】:

如何使用运行时在一秒钟内退出循环? 我想用这个代码

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


       }
}

【问题讨论】:

  • 请详细说明您想做什么。
  • 我想计算一秒钟内可以添加多少字符串,例如 while (somthing

标签: java runtime timeunit


【解决方案1】:
long startTime = System.currentTimeMillis();

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

【讨论】:

  • 我想计算一秒钟内可以添加多少字符串,例如 while (somthing
  • ` long startTime = System.currentTimeMillis();字符串 str ="a"; while((System.currentTimeMillis()-startTime)
  • 我可以打印 str.length() 但不能打印 str !!
【解决方案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);

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

【讨论】:

  • 那是因为我没有把你的代码放在我的代码里。我只是发表评论说//做你的事情。我会更新的。
  • 在我的慢速机器上,我可以做大约 37443 次。 System.out.println (str1.length());
  • 我可以打印 str.length() 但不能打印 str !!
  • 请在您的问题中更新您的代码。然后我们就可以看到问题所在了。
【解决方案3】:
 long startTime = System.currentTimeMillis();
 while((System.currentTimeMillis()-startTime)<1000){
// Your task goes here
}

【讨论】:

  • 我想计算一秒钟内可以添加多少字符串,例如 while (somthing
【解决方案4】:

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

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

【讨论】:

    【解决方案5】:

    如果你真的不需要使用运行时,我认为你可以使用这样的东西。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-18
      • 2022-01-15
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多