Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.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 - Fatal编程技术网

如何使用计时器在Java中运行方法?

如何使用计时器在Java中运行方法?,java,Java,如何让这个方法在递归函数中每隔几秒钟运行一次。 我希望I变量每隔几秒钟更新1次,然后将其打印到控制台。 在javascript中,我可以使用setTimeout,Java中是否有类似javascript setTimeout的方法 final i = 0; public void timerActions() { i = i + 1; System.out.println(i); } 为此,您应该使用ScheduledExecutorService 根据Peter Lawr

如何让这个方法在递归函数中每隔几秒钟运行一次。 我希望I变量每隔几秒钟更新1次,然后将其打印到控制台。 在javascript中,我可以使用setTimeout,Java中是否有类似javascript setTimeout的方法

final i = 0;
public void timerActions() {
     i = i + 1;
     System.out.println(i);
}

为此,您应该使用
ScheduledExecutorService

根据Peter Lawrey评论更新(谢谢):

方法:

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                              long initialDelay,
                                              long period,
                                              TimeUnit unit);
public ScheduledFuture scheduleAtFixedRate(Runnable命令,
长时间的延迟,
长期以来,,
时间单位);

public ScheduledFuture scheduleWithFixedDelay(Runnable命令,
长时间的延迟,
久拖不决,,
时间单位);

可以用来实现您想要的行为。

您可以在执行后将
线程
置于休眠状态,如果它只是一个简单的应用程序,只需要“运行得更慢”

例如:

final i = 0;
public void timerActions() {
    i++;
    System.out.println(i);
    Thread.sleep(1000);
}
括号中的1000表示1000ms=1秒—线程休眠的时间量。 这是一种简单的方法,但请注意,在大型多线程应用程序中,您必须考虑线程安全和相关问题

试用计时器的文档

Timer timer = new Timer("Display Timer");

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                timerActions();
            }
        };
        // This will invoke the timer every second
        timer.scheduleAtFixedRate(task, 1000, 1000);
    }
这将每隔2秒打印一次“计数…”

import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

private int counter = 0;

public void run() {
    counter++;
    if (counter <= 3) {
        System.out.println("Counting - counter = " + counter);
    } else {
        System.out.println("Stopping timer execution");
        this.cancel();
    }
}


public static void main(String[] args) {

    Timer timer = new Timer("TimerThreadName");
    MyTimerTask task = new MyTimerTask();

    // void java.util.Timer.schedule(TimerTask task, long delay, long period)
    timer.schedule(task, 0, 2000);

    }
}
import java.util.Timer;
导入java.util.TimerTask;
公共类MyTimerTask扩展了TimerTask{
专用整数计数器=0;
公开募捐{
计数器++;

如果(计数器)您可以使用
Thread.sleep(1000);
如果这只是为了好玩,那么日程表只执行一次。
public class TimedAction
{
    public static void main(String[] args) throws Exception
    {
        System.out.println("begin");

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        Runnable command = new Runnable()
        {
            private int i = 0;

            @Override
            public void run()
            {
                // put your logic HERE
                System.out.println(i++);
            }
        };

        // execute command, immediately (0 delay), and every 2 seconds
        executor.scheduleAtFixedRate(command, 0, 2, TimeUnit.SECONDS);

        System.in.read();

        executor.shutdownNow();
        executor.awaitTermination(5, TimeUnit.SECONDS);

        System.out.println("end");
    }
}
import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

private int counter = 0;

public void run() {
    counter++;
    if (counter <= 3) {
        System.out.println("Counting - counter = " + counter);
    } else {
        System.out.println("Stopping timer execution");
        this.cancel();
    }
}


public static void main(String[] args) {

    Timer timer = new Timer("TimerThreadName");
    MyTimerTask task = new MyTimerTask();

    // void java.util.Timer.schedule(TimerTask task, long delay, long period)
    timer.schedule(task, 0, 2000);

    }
}