2012-04-16 67 views
2

我有一個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"); 
    } 

}

+1

你有什麼試過的?你有沒有讀過[Java的併發介紹](http://docs.oracle.com/javase/tutorial/essential/concurrency/)? – 2012-04-16 15:31:52

+0

您可能想要使用線程池。無論如何,只要在For中創建線程對於遇到線程的人來說不應該是個問題。 – 2012-04-16 15:34:05

+0

我試圖在public void函數內創建線程,並且每創建一個線程的新實例並在最後運行它。但是。這沒有幫助:( – ZhiZha 2012-04-16 15:40:15

回答

0

創建一個新類主類中,並在內部類
做你的業務的每次你需要創建一個新的線程剛剛開始一個新的內部類的實例,並調用其爲此目的而創建的方法
如果您覺得此回答無用,請查看我的其他多線程答案。

+1

噢好主意。我會嘗試並給它一個鏡頭 – ZhiZha 2012-04-16 15:40:45

2

一個做這些類型的任務是,首先,創建一個類來保存你想從每個線程得到的結果一般方式:

final class PingResult { 
    public String ip; 
    public String hostname; 
    //... other things you want go here 
} 

然後創建一個可調用的,做實際工作

class PingTask extends Callable<PingResult>{ 
    private final String gateWayKey, subNetKey; 
    //... other parameters you need go here 
    public Ping(String gwKey, String snKey /*+ others? */){ 
     // This is just a way to pass parameters to your pinging function 
     this.gateWayKey = gwKey; 
     this.subNetKey = snKey; 
     // ... 
    } 

    public PingResult call(){ 

     // Do actual pinging work here 

     if (/* Success */) 
     { 
      PingResult result = new PingResult(); 
      result.ip= /*Fill these in*/; 
      result.hostname = /* ... */; 
      return result; 
     } 
     // Otherwise we failed, I'm using null as a failure sentinel 
     // (you can come up with something better) 
     return null; 
    } 
} 

然後在您的調用代碼中,設置線程池,提出請求,然後處理結果。

// Might need to tweak the # for best performance 
final int NUM_THREADS = Runtime.getRuntime.availableProcesses(); 
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); 

List<Future<PingResult>> results = new ArrayList<PingResult>(); 

for(/* ... */){ 
    results.add(exec.submit(new PingTask(gateway, subnet))); 
} 

for(Future<PingResult> future : results){ 
    PingResult result = future.get(); 

    // Process the result here (this is where you insert into the DB) 
} 

exec.shutdown(); // VERY IMPORTANT. If you don't do this the JVM will never stop. 
相關問題