我有一個ping IP地址的類。要啓動ping,我有公共vod run()方法來啓動ping。問題是我想同時ping更多的IP地址(每個IP地址我需要新的線程)。那麼如何在循環內部創建新的線程。這裏是我的ping類代碼:在public void method中創建新線程()
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");
}
}
你有什麼試過的?你有沒有讀過[Java的併發介紹](http://docs.oracle.com/javase/tutorial/essential/concurrency/)? – 2012-04-16 15:31:52
您可能想要使用線程池。無論如何,只要在For中創建線程對於遇到線程的人來說不應該是個問題。 – 2012-04-16 15:34:05
我試圖在public void函數內創建線程,並且每創建一個線程的新實例並在最後運行它。但是。這沒有幫助:( – ZhiZha 2012-04-16 15:40:15