这是代码:
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");
}
}
假设有一个类NetworkDiscovery有一个run(),并且其上的所有内容都可以正常工作,那么println()就不会被执行。为什么这样?
是否还有其他方法可以在后台重复执行操作,同时执行其他操作?
答案 0 :(得分:4)
当我尝试使用以下虚拟实现时,它似乎像宣传的那样工作:
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");
}
}
我得到以下输出:
null
NetworkDiscovery
NetworkDiscovery
...(every 2000 milliseconds)...
答案 1 :(得分:1)
您发布的代码会创建计时器,System.out.println("null");
会在该实例化后立即运行,而不是计时器类的一部分。
所以,你的输出原样是:
null <- only happens once
[output from NetworkDiscovery() method]
[output from NetworkDiscovery() method]
[output from NetworkDiscovery() method] <- repeated every 2 seconds