开发者

Code after TImer execution not working

This is the c开发者_StackOverflow社区ode:

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");
    }
}

Assuming that there is a class NetworkDiscovery which has a run() and everything on that works fine, the println() alone doesn't get executed. Why so?

Is there another way to repeatedly perform an action in the background while other actions are performed too?


When I tried it with the following dummy implementation, it seems to work as advertised:

import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

public class Controller {

    private static final class NetworkDiscovery extends TimerTask {
        @Override
        public void run() {
            System.out.println("NetworkDiscovery");
        }
    }

    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");
    }
}

I get the following output:

null
NetworkDiscovery
NetworkDiscovery
...(every 2000 milliseconds)...


The code you posted creates the timer, and System.out.println("null"); runs immediately after that instantiation, not part of the timer class.

So, your output, as-is, would be:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜