这是代码:

public class Controller {
    NetworkDiscovery n;
    public static int discoveryInterval=2000;

    public static void main(String[] args) throws UnknownHostException{
        Timer t1=new Timer();
        t1.scheduleAtFixedRate(new NetworkDiscovery(), 2000, discoveryInterval);
        System.out.println("null");
    }
}


假设存在一个具有run()的NetworkDiscovery类,并且该类上的所有东西都工作正常,则仅println()不会被执行。为什么这样?

是否还有另一种方法可以在后台重复执行某个动作,同时也执行其他动作?

最佳答案

您发布的代码将创建计时器,并且System.out.println("null");在实例化后立即运行,而不是计时器类的一部分。

因此,您的输出将是:

null                                      <- only happens once
[output from NetworkDiscovery() method]
[output from NetworkDiscovery() method]
[output from NetworkDiscovery() method]   <- repeated every 2 seconds

07-24 21:29