2013-03-11 84 views
6

我有一個Runnable對象,一個運行ping操作 - 如果我推出這個在當前線程這樣爲什麼我的過程終止?

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(); 
       } 
      } 
     }; 

r1.run(); 

我得到這樣的輸出:

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 

但如果我在像這樣的新線程中運行它:

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

我得到這個:

Before process 

爲什麼輸出不同?

回答

8

如果您在單獨的線程中運行,您的主線程可能會在之前完成,因此您的r1將沒有足夠的時間完成。如果你從當前線程開始,你會等到完成。嘗試在開始後添加thread.join(),看看發生了什麼。

+0

它的工作原理,謝謝! – 2013-03-11 19:47:24

+3

或者在開始之前添加'thread.setDaemon(false)'。這將防止主線程終止時新線程停止。 – buc 2013-03-11 19:47:26