简体   繁体   English

无限循环通过列表,枚举

[英]infinite loop through a list, enumeration

So im building an application in swing that will ping a url or a list of urls to show the machines status. 所以我在swing中构建一个应用程序,它将ping一个url或url列表以显示机器状态。 So if a machine disconnects it will show up as disconnected. 因此,如果机器断开连接,它将显示为断开连接。 I have a list of machines but I need it to loop over forever in intervals so I can know the status of the machine. 我有一个机器列表,但我需要它间隔永远循环,所以我可以知道机器的状态。 I know you cant reset the enumeration count so im stuck on a workaround for it. 我知道你无法重置枚举计数,所以我坚持一个解决方法。

Currently the part of the code that does the pinging and enumeration is below: 目前,执行ping和枚举的代码部分如下:

class WorkerThread extends Thread { 
DefaultListModel model;

public WorkerThread(DefaultListModel aModel) { 
    model = aModel; 
} 

public void run() { 
Pinging ping = new Pinging();
int num ;
Enumeration<String> e;


for ( e= model.elements(), num=0; e.hasMoreElements(); num ++){
    String element = e.nextElement();
    for (int i = 0; i<5; i++){
    ping.reachUrl(element);
      //ping.timer(5, e.nextElement()); 
        final int pos = num;
        EventQueue.invokeLater(new Runnable() { 
            public void run() { 
                //ping.reachUrl(e.nextElement());
                String name = ping.getName();
                String addr = ping.getAddr();
                boolean reach = ping.getReach();
                int time = ping.getTime();
                model.set(pos, name+"  " + addr+"  " + reach + "  " + time);
                //model.add(pos, name+"  " + addr+"  " + reach + "  " + time);
                //model.set(pos, "Hello");

            } 
        }); 

        yield(); 
    }



}

} 

} }

Use a List rather than an Enumeration . 使用List而不是Enumeration

Maintain an int that records your place in the list, and when you get to the end of the list, start again at the beginning. 保持一个记录您在列表中的位置的int ,当您到达列表的末尾时,从头开始。

But really you want a separate thread for each URL that you're watching. 但实际上,您需要为您正在观看的每个URL设置一个单独的线程。 And you certainly don't want to be doing the ping calls on the event thread. 你当然不希望在事件线程上进行ping调用。 Use a SwingWorker , so that it can run in the background and still update the GUI using the done() method when it's finished. 使用SwingWorker ,以便它可以在后台运行,并在done()使用done()方法更新GUI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM