我需要帮助理解 java 中 Timer 类的 scheduleAtFixedRate 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15571169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:06:37  来源:igfitidea点击:

I need help understanding the scheduleAtFixedRate method of theTimer class in java

javasyntax

提问by dwwilson66

Being a fan of the Pomodoro techniqueI'm making myself a countdown timer to keep me on task with my homework. This particular project, however, is NOT homework. :)

作为番茄工作法的粉丝,我让自己成为一个倒数计时器,让我继续完成家庭作业。然而,这个特定的项目不是家庭作业。:)

Stack has a LOT of questions about using timers to control delays before user input and the like, but not a lot on standalone timers. I've run across this code from a friend, and have studied the class on Java Documentation.

Stack 有很多关于在用户输入之前使用计时器来控制延迟等问题,但在独立计时器上没有很多问题。我从朋友那里看到了这段代码,并研究了 Java 文档中的课程。

public class Stopwatch {
    static int interval;
    static Timer timer;

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Input seconds => : ");
        String secs = sc.nextLine();
        int delay = 1000;
        int period = 1000;
        timer = new Timer();
        interval = Integer.parseInt( secs );
        System.out.println(secs);
        timer.scheduleAtFixedRate(new TimerTask()
        {
            public void run()
            {
                System.out.println(setInterval());
            }
        }, delay, period);
    }
    private static final int setInterval()
    {
        if( interval== 1) timer.cancel();
        return --interval;
    }
}

There is some syntax that's not clear to me. Consider:

有一些语法我不清楚。考虑:

timer.scheduleAtFixedRate(new TimerTask()
{
     public void run()
     {
          System.out.println(setInterval());
     }
}, delay, period);

I'm not understanding how the parentheses and braces work. At first glance, given the usage of scheduleAtFixedRate(TimerTask task, long delay, long period)I can see the delayand periodparameters, but not an open paren preceding first parameter.

我不明白括号和大括号是如何工作的。乍一看,鉴于使用scheduleAtFixedRate(TimerTask task, long delay, long period)I 可以看到delayperiod参数,但在第一个参数之前看不到开放括号。

Is my first parameter actually this whole block of code? I would expect the whole block to be surrounded by parentheses...but it's not. Is this a common syntax in java? I've never run across it before.

我的第一个参数实际上是整个代码块吗?我希望整个块都被括号包围......但事实并非如此。这是java中的常见语法吗?我以前从未遇到过它。

new TimerTask() { public void run() { System.out.println(setInterval()); } }

new TimerTask() { public void run() { System.out.println(setInterval()); } }

I just want to clarify that I understand it before I start mucking about with changes.

我只是想澄清一下,在我开始考虑更改之前,我理解它。

回答by John Kugelman

timer.scheduleAtFixedRate(new TimerTask()
{
     public void run()
     {
          System.out.println(setInterval());
     }
}, delay, period);

That code is equivalent to this refactoring, where the new TimerTaskis assigned to a local variable.

该代码等效于此重构,其中将new TimerTask分配给局部变量。

TimerTask task = new TimerTask()
{
     public void run()
     {
          System.out.println(setInterval());
     }
};

timer.scheduleAtFixedRate(task, delay, period);

Of course the weird part has just moved upwards a bit. What is this new TimerTaskstuff, exactly?

当然,奇怪的部分只是向上移动了一点。这到底是什么new TimerTask东西?

Java has special syntax for defining anonymous inner classes. Anonymous classes are a syntactical convenience. Instead of defining a sub-class of TimerTaskelsewhere you can define it and its run()method right at the point of usage.

Java 具有用于定义匿名内部类的特殊语法。匿名类是一种语法便利。TimerTask您可以在使用时定义它及其run()方法,而不是在别处定义子类。

The code above is equivalent to the following, with the anonymous TimerTasksub-class turned into an explicit named sub-class.

上面的代码等价于下面的代码,匿名TimerTask子类变成了显式命名子类。

class MyTimerTask extends TimerTask
{
     public void run()
     {
          System.out.println(setInterval());
     }
}

TimerTask task = new MyTimerTask();
timer.scheduleAtFixedRate(task, delay, period);

回答by Keppil

You are correct, the first parameter is the entire code block:

你是对的,第一个参数是整个代码块:

new TimerTask()
{
     public void run()
     {
          System.out.println(setInterval());
     }
}

These declarations are called Anonymous classesand are explained in more detail in the Java Tutorials.

这些声明称为匿名类,在Java 教程中有更详细的解释。

回答by Ankur Shanbhag

It is a anonymous inner class. You need to study inner classes for understanding this. Generally such classes are used when you do not need the class to be used else where in your code. You cannot use it else where just because you dont have reference pointing to it.You can also replace the above code as follows :

它是一个匿名内部类。你需要学习内部类来理解这一点。通常,当您不需要在代码中的其他位置使用该类时,会使用此类类。你不能在其他地方使用它,因为你没有指向它的引用。您还可以按如下方式替换上面的代码:

class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            // Timer task code goes here.
             System.out.println(setInterval());
        }

    }
    MyTimerTask timerTask = new MyTimerTask();
    timer.scheduleAtFixedRate(timerTask, delay, period);