2012-04-16 15 views
2

IPアドレスをpingするクラスがあります。 pingを開始するには、pingを開始するpublic vod run()メソッドがあります。問題は、同時に(IPアドレスごとに新しいスレッドが必要)、より多くのIPアドレスにpingをしたいということです。それでは、どのように新しいThread inside forループを作成できますか?forループ内に新しいスレッドを作成する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/)を読んだことがありますか? –

+0

スレッドのプールを使用することができます。とにかく、Forのスレッドを作成するだけで、スレッドを経験している人にとっては問題にならないはずです。 –

+0

私はpublic void関数内でスレッドを作成しようとしましたが、すべてのループでスレッドの新しいインスタンスを作成し、最後に実行していました。しかし、ofc。それは助けなかった:( – ZhiZha

答えて

0

は、あなただけの開始新しいスレッドを作成する必要があり、すべてのタイムをあなたのメインクラス内で新しいクラスを作成し、その内部クラス
であなたの操作を行います。ここに私のpingクラスのコードがありますその内部クラスの新しいインスタンスとその目的のために作成されたメソッドを呼び出す
この答えが役に立たないとわかったら、マルチスレッドに関する私の他の答えをチェックしてください。

+1

ああいいアイデア。私はそれを試して、それを与えるショット – ZhiZha

2

A、まず、あなたはそれぞれのスレッドから取得したい結果を保持するクラスを作成されたタスクのこれらの種類を行うための一般的な方法:

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. 
関連する問題