【问题标题】:Is there a way to slow down a variable++; function?有没有办法减慢变量++;功能?
【发布时间】:2014-01-01 21:45:03
【问题描述】:

我需要一个变量来向上计数,但增量为 2 秒。现在我只是在使用++; 函数,但你知道它非常快。

有什么简单的方法可以让我以较慢的速度计数吗?

【问题讨论】:

标签: java timer


【解决方案1】:
Thread.sleep(2000);

这将使您的程序在此方法调用和紧随其后的任何执行行之间等待 2 秒。

【讨论】:

    【解决方案2】:
    public class Count implements Runnable{
      public void run(){
         for(int i=0;i<=6;i+=2){
             Thread.sleep(2000)//in milliseconds ...sleeping for 2 sec
             sysout(...);//print your value
           }
       }
    }
    

    这样开始

    Runnable r=new Count();
    Thread t=new Thread(r);
    t.start(); // start the  thread
    

    你所做的基本上是做一个线程并延迟运行。我希望你得到一个概念

    【讨论】:

      【解决方案3】:

      是的,您可以使用 Thread.sleep(2000) 暂停执行两秒钟。

      //Your code...
      Thread.sleep(2000);
      counter = counter + 2;
      //Your code...
      

      【讨论】:

        【解决方案4】:

        这将从 1 打印到 99,以 2 为增量,增量之间有 1 秒的停顿。

        public static void main(String[] args) {
          for (int i = 1; i < 100; i += 2) { // i = i + 2
            System.out.printf("i = %d\n", i); // print i = #
            try {
              Thread.sleep(2000); // two seconds.
            } catch (InterruptedException e) {
            }
          }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-07
          • 2020-12-04
          • 2021-06-22
          • 1970-01-01
          相关资源
          最近更新 更多