Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java循环一定的持续时间_Java_Time_Loops - Fatal编程技术网

Java循环一定的持续时间

Java循环一定的持续时间,java,time,loops,Java,Time,Loops,有没有一种方法可以让我在一定时间内轻松地进行for循环?(不使用System.currentTimeMillis()测量时间) 也就是说,我想在Java中做类似的事情: int x = 0; for( 2 minutes ) { System.out.println(x++); } 谢谢否。考虑到编写一个使用System.currentTimeMillis()的函数(或您选择的任何时间函数)是多么简单,这是一个奇怪的请求。这种情况可能需要更多的上下文。我不认为有一种方法可以循环一段时间

有没有一种方法可以让我在一定时间内轻松地进行for循环?(不使用System.currentTimeMillis()测量时间)

也就是说,我想在Java中做类似的事情:

int x = 0;
for( 2 minutes )  {
   System.out.println(x++);
}

谢谢

否。考虑到编写一个使用System.currentTimeMillis()的函数(或您选择的任何时间函数)是多么简单,这是一个奇怪的请求。这种情况可能需要更多的上下文。

我不认为有一种方法可以循环一段时间而不检查您是否已经循环了一段时间。

根据您的用例,类中的两个sleep()方法中的任何一个都可能符合要求,但听起来你不得不对System.currentTimeMillis()大惊小怪,这似乎很奇怪

Thread thread = Thread.currentThread();
thread.sleep(10);      // 10 milliseconds
thread.sleep(12, 345); // 12 milliseconds and 345 nanoseconds.

循环在值比较上迭代,而不是持续时间。因此,如果没有自己分配和比较系统时间,您就无法完成这项工作。 如果您希望它是直观的,那么您可以拥有一个函数,该函数在内部使用毫秒,但以分钟作为参数并使用它


不,您不能在其中使用线程或sleep方法,因为这不能确保准确的时间。如果处理器在给定时间后忙于处理其他线程,那么线程将继续等待。

不,没有内置的结构可以完成此任务

我想指出,您不应该使用System.currentTimeMillis()在指定的时间段内执行或延迟任务。而是使用System.nanoTime()。前一种方法在Windows中是不准确的,而后一种方法无论操作系统如何都是准确的。您可以使用TimeUnit enum轻松地将时间(毫秒)或任何其他时间单位转换为时间(纳秒)

for (long stop=System.nanoTime()+TimeUnit.SECONDS.toNanos(2);stop>System.nanoTime();) {
  /*
   * Hammer the JVM with junk
   */
}

我想这就是你想要的:

private final Thread thisThread = Thread.current();
private final int timeToRun = 120000; // 2 minutes;

new Thread(new Runnable() {
    public void run() {
        sleep(timeToRun);
        thisThread.interrupt();
    }
}).start();

while (!Thread.interrupted()) {
    // do something interesting.
}
这避免了重复进行系统调用以获取系统时钟值(这可能相当昂贵),并轮询当前线程的
interrupted
标志(更便宜)

编辑

除了轮询时钟或轮询标志外,实际上没有安全的替代方法。理论上,您可以修改上面的片段来调用不推荐使用的
Thread.stop()
方法,而不是
Thread.interrupt()

(我不建议使用
Thread.stop()
和friends。它们有缺陷,使用起来很危险。我只是把它当作一个理论上的替代品。)

编辑2

只需指出,使用
Thread.interrupt()
比设置共享标志有优势:

  • Thread.interrupt()将导致某些阻塞I/O和同步方法取消阻塞并引发已检查的异常。更新共享标志不会执行此操作

  • 一些第三方库还检查中断标志,查看是否应该停止当前正在执行的操作

  • 如果您的循环涉及对其他方法的调用等,Thread.interrupt()意味着您不必担心这些方法可以访问标志。。。如果他们需要的话

编辑3


只需补充一点,
sleep(N)
不能保证在
N
毫秒之后唤醒睡眠线程。但在正常情况下,它将相当接近。

这里有另一个建议:

}

该方法重复执行提供的
Runnable
run()
方法,直到计时器过期

考虑事项:

  • 时间将是大约的
  • 请注意如何实现
    run()
    方法,因为它可能会消耗您所有的CPU电源。
  • 除非为要执行的每个
    Runnable
    创建
    TimerLoop
    类的新实例,否则该实现不是线程安全的。

    • 我为这个问题做了一个简单但糟糕的实现。我想避免使用计时器和TimeTask,最终得到了这个快速修复解决方案

      主要的想法是,我只是想创建一个独立的倒计时计时器,我可以启动它并调用isFinished()来检查倒计时是否完成

       package RIPv3;
      
      /**
       * Used by CountdownTimer to count down time.
       * 
       * @author Endre Vestbø
       * @version 1.0  (09.05.2011)
       *
       */
      public class CountdownTimerThread extends Thread {
      private long time;
      
      /** Create a new timer */
      public CountdownTimerThread(long time) {
          this.time = time;
      }
      
      /**
       * Start a countdown
       * @param period
       *      Period to count down given in milliseconds
       */
      public void run() {
          try {
              sleep(this.time);
          } catch (InterruptedException e) {
      
          }
      }
      }
      


      您想在屏幕上连续、激烈地打印2分钟的内容吗?或者你想每2分钟打印一次?我想在屏幕上连续地、疯狂地打印一些东西,持续2分钟。大多数答案都完全错了,说如果你不自己测量时间,你就做不到。您完全可以不使用System.currentTimeMillis()完成此操作。例如,您可以将计时器设置为两分钟,以更改易失性布尔值(比如shouldStop)并使用while(!shouldStop){…},但实际上,对于这么简单的事情,我看不出使用System.currentTimeMillis()有什么问题(请注意,即使我更喜欢System.currentTimeMillis())顺便说一句,Java不是实时的,即使不断地检查System.currentTimeMillis(),也不能保证您能够运行整整两分钟:您的线程疯狂地检查时间可能会被“安排出去”,您可能会“错过”确切的时间无论如何,两分钟就可以了,所以争论计时器可能会漏掉标记是相当迟钝的,因为线程不断地检查系统。currentTimeMillis()也可能漏掉标记:)哦,奇才们,太热情了,太生气了。我有一个朋友给你。+0.5,因为你以23秒的优势击败了我+0.5来指出请求的奇怪之处。@MaxGuernseyll-实际上,调用
      System.currentTimeMillis()
      可能会非常昂贵。在某些平台上,需要进行系统调用;i、 数以百计的机器指令。奇怪的要求并不意味着愚蠢的问题?如果你这样说。。。不管怎样,“否”显然是一个错误的答案。@Stephen如果我们使用system.c,平均一秒钟内进行了多少次系统调用
      package RIPv3;
      
      /**
       * Creates a countdown timer which runs its own thread and uses CountdownTimerThread,                which runs yet another
       * thread.
       *
       * start() method is called to start the countdown.
       * isFinished() method is called to check if the countdown is finished or not.
       * 
       * ! Be Aware!
       * This is a quickfix and sucky implementation.
       * There will be a small delay. This is not accurate.
       * 
       * @author Endre Vestbø
       * @version 1.0 (09.05.2011)
       */
      public class CountdownTimer extends Thread {
      /* Countdown timer */
      private CountdownTimerThread timer;
      
      /**
       * Creates a new timer and sets time to count down
       * @param time
       *          Time to count down
       */
      public CountdownTimer(long time) {
          this.timer = new CountdownTimerThread(time);
      }
      
      public void run() {
          this.timer.start();
      }
      
      /**
       * @return
       *      False if timer is running, else true
       */
      public boolean isFinished() {
          if(this.timer.getState() == Thread.State.TERMINATED)
              return true;
      
          return false;
      }   
      }
      
       package RIPv3;
      
      /**
       * Used by CountdownTimer to count down time.
       * 
       * @author Endre Vestbø
       * @version 1.0  (09.05.2011)
       *
       */
      public class CountdownTimerThread extends Thread {
      private long time;
      
      /** Create a new timer */
      public CountdownTimerThread(long time) {
          this.time = time;
      }
      
      /**
       * Start a countdown
       * @param period
       *      Period to count down given in milliseconds
       */
      public void run() {
          try {
              sleep(this.time);
          } catch (InterruptedException e) {
      
          }
      }
      }