我有一个 ping IP 地址的类。要开始 ping,我有公共 vod run() 方法来开始 ping。问题是我想同时 ping 更多的 IP 地址(对于每个 IP 地址我需要新的线程)。那么如何在 for 循环中创建新线程。这是我的 ping 类的代码:
public void run()
{
if (dbConnection.ConnectToDB())
{
for (;GateWayKey<=GateWayKeyStop;GateWayKey++)
{
if(stop || this.isInterrupted()){
return;
}
ip="192.168."+GateWayKey+".1";
InetAddress address;
try {
address = InetAddress.getByName(ip);
try {
if (address.isReachable(PingTime))
{
//System.out.println("Pronaden GateWay: "+ip)
// labele.IP
sql="INSERT INTO `iptables` (`IP` , `COMPUTER_NAME` , `GATEWAY_KEY`) VALUES ('"+ip+"', '"+address.getHostName().toString()+"', '"+GateWayKey+"');";
framedocs.WriteMonitorData (ip, address.getHostName().toString(),"2000","DA",dbConnection.WriteToDB(sql));
for (;SubNetKey<=SubNetKeyStop;SubNetKey++)
{
if(stop || this.isInterrupted()){
return;
}
InetAddress addressIps = InetAddress.getByName("192.168."+GateWayKey+"."+SubNetKey);
System.out.println("Provjeravam IP: "+addressIps);
if (addressIps.isReachable(PingTime))
{
ip="192.168."+GateWayKey+"."+SubNetKey;
System.out.println("Pronaden IP: "+ip);
sql="INSERT INTO `iptables` (`IP` , `COMPUTER_NAME` , `GATEWAY_KEY`) VALUES ('"+ip+"', '"+addressIps.getHostName().toString()+"', '"+GateWayKey+"');";
framedocs.WriteMonitorData (ip, address.getHostName().toString(),"2000","DA",dbConnection.WriteToDB(sql));
}
else
{
framedocs.WriteMonitorData (addressIps.toString(), "N/A","2000","NE","N/A");
}
}
}
else
{
framedocs.WriteMonitorData (ip, "N/A","2000","NE","N/A");
}
} catch (IOException e) {
// TODO Auto-generated catch block
framedocs.WriteMonitorData (ip, "N/A","2000",e.getMessage(),"N/A");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
;
framedocs.WriteMonitorData (ip, "N/A","2000",e.getMessage(),"N/A");
}
}
}
else
{
framedocs.WriteMonitorData ("MySQL error", "N/A","N/A","N/A","N/A");
}
}