2013-03-11 12 views
6

Ich habe ein Runnable-Objekt, das einen Ping-Betrieb läuft -Warum endet mein Prozess?

Runnable r1 = new Runnable() { 
      @Override 
      public void run() { 
       try{ 
        List<String> commands = new ArrayList<String>(); 
        commands.add("ping"); 
        commands.add("-c"); 
        commands.add("10"); 
        commands.add("google.com"); 

        System.out.println("Before process"); 
        ProcessBuilder builder = new ProcessBuilder(commands); 
        Process process = builder.start(); 

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 
        String line = null; 
        while ((line=reader.readLine()) != null){ 
         System.out.println(line); 
        } 
        process.waitFor(); 
        System.out.println("After process"); 

       }catch (Exception ex){ 
        ex.printStackTrace(); 
       } 
      } 
     }; 

Wenn ich dies in aktuellen Thread wie folgt starten:

r1.run(); 

ich diese Ausgabe erhalten:

Before process 
PING google.com (173.194.32.33): 56 data bytes 
64 bytes from 173.194.32.33: icmp_seq=0 ttl=53 time=34.857 ms 
64 bytes from 173.194.32.33: icmp_seq=1 ttl=53 time=39.550 ms 
64 bytes from 173.194.32.33: icmp_seq=2 ttl=53 time=44.212 ms 
64 bytes from 173.194.32.33: icmp_seq=3 ttl=53 time=38.111 ms 
64 bytes from 173.194.32.33: icmp_seq=4 ttl=53 time=39.622 ms 
64 bytes from 173.194.32.33: icmp_seq=5 ttl=53 time=41.391 ms 
64 bytes from 173.194.32.33: icmp_seq=6 ttl=53 time=41.280 ms 
64 bytes from 173.194.32.33: icmp_seq=7 ttl=53 time=39.645 ms 
64 bytes from 173.194.32.33: icmp_seq=8 ttl=53 time=35.931 ms 
64 bytes from 173.194.32.33: icmp_seq=9 ttl=53 time=38.245 ms 

--- google.com ping statistics --- 
10 packets transmitted, 10 packets received, 0.0% packet loss 
round-trip min/avg/max/stddev = 34.857/39.284/44.212/2.575 ms 
After process 

Aber wenn ich es in einem neuen Thread wie folgt ausführen:

Thread thread = new Thread(r1); 
    thread.start(); 

ich dieses:

Before process 

Warum sind die verschiedenen Ausgänge?

Antwort

8

Wenn Sie in einem separaten Thread laufen, wird Ihr Haupt-Thread wahrscheinlich vorher beendet, so dass Ihre r1 nicht genug Zeit haben wird, um zu beenden. Wenn Sie im aktuellen Thread starten, warten Sie bis zum Ende. Versuchen Sie nach dem Start thread.join() hinzuzufügen und sehen Sie, was passiert.

+0

Es funktioniert, danke! –

+3

Oder fügen Sie 'thread.setDaemon (false)' vor dem Start hinzu. Dies verhindert, dass der neue Thread beendet wird, wenn der Haupt-Thread beendet wird. – buc

Verwandte Themen