有 Java 编程相关的问题?

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

java使用系统每秒运行一次代码。currentTimeMillis()

我试图通过使用系统每秒运行一行代码。currentTimeMillis()

守则:

     while(true){
           long var = System.currentTimeMillis() / 1000;
           double var2 = var %2;

           if(var2 == 1.0){

               //code to run

           }//If():

        }//While

我想要运行的代码运行了多次,因为var2由于无限的整个循环被多次设置为1.0。我只想在var2第一次设置为1.0时运行代码行,然后在var2在0.0之后变为1.0时再次运行代码行


共 (5) 个答案

  1. # 1 楼答案

    首选方式:

    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    

    然后传入Runnable,如:

    scheduler.scheduleWithFixedDelay(myRunnable, initDelay, delay, TimeUnit.MILLISECONDS);
    

    我不会用计时器。调度器是用来处理计时器可能引起的问题的。还有,线。睡眠对于一个简单的程序来说是很好的,你正在快速编写这个程序来证明概念类型的东西,但是我不会在企业界使用它

  2. # 2 楼答案

    使用Thread.sleep();将非常适合您的情况

     while(true)
     {
        Thread.sleep(1000); // Waiting before run.
        // Actual work goes here.
     }
    
  3. # 3 楼答案

    我会使用javaexecutor库。您可以创建一个ScheduledPool,该ScheduledPool接受runnable并可以运行任意时间段。比如说

    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new MyRunnable(), 0, 5, TimeUnit.SECONDS);
    

    将每5秒运行一次MyRunnable类。MyRunnable必须实现Runnable。这样做的问题是,它每次都(有效地)创建一个新线程,这可能是可取的,也可能是不可取的

  4. # 5 楼答案

    如果您想等待秒数更改,可以使用以下命令

    long lastSec = 0;
    while(true){
        long sec = System.currentTimeMillis() / 1000;
        if (sec != lastSec) {
           //code to run
           lastSec = sec;
        }//If():
    }//While
    

    更有效的方法是睡到下一秒

    while(true) {
        long millis = System.currentTimeMillis();
        //code to run
        Thread.sleep(1000 - millis % 1000);
    }//While
    

    另一种方法是使用ScheduledExecutorService

    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    
    ses.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            // code to run
        }
    }, 0, 1, TimeUnit.SECONDS);
    
    // when finished
    ses.shutdown();
    

    这种方法的优点是

    • 您可以有多个不同时段的任务共享同一线程
    • 您可以有非重复延迟或异步任务
    • 您可以在另一个线程中收集结果
    • 您可以使用一个命令关闭线程池