2016-04-30 82 views
2

我正在使用ProcessBuilder啓動外部進程,但我需要能夠殺死它。現在我沒有任何問題可以終止進程,但由於某種原因,錯誤流不會關閉,因此讀取流的線程永遠不會結束。這使我無法關閉我的程序。Java停止進程和關閉流

這裏是我開始從輸入和錯誤流中讀取線程的地方。

   final Thread inputPrinter = new Thread() { 
        public void run() { 
         BufferedReader inputStream = new BufferedReader(new InputStreamReader(builder.getInputStream())); 
         String line; 
         try { 
          while ((line = inputStream.readLine()) != null) { 
           Util.println(line, false); 
          } 
         } catch (IOException e) { 
         } finally { 
          Util.println("input end"); 
          try { 
           inputStream.close(); 
          } catch (IOException e) { 
          } 
         } 
        } 
       }; 
       inputPrinter.start(); 

       Thread errorPrinter = new Thread() { 
        public void run() { 
         BufferedReader errorStream = new BufferedReader(new InputStreamReader(builder.getErrorStream())); 
         String line; 
         try { 
          while ((line = errorStream.readLine()) != null) { 
           Util.println(line, true); 
          } 
         } catch (IOException e) { 
         } finally { 
          Util.println("error end"); 
          try { 
           errorStream.close(); 
          } catch (IOException e) { 
          } 
         } 
        } 
       }; 
       errorPrinter.start(); 
       builder.waitFor(); 

       Util.println(""); 
       Util.println("Finished building project."); 

這是我的代碼,用於停止進程。

 try { 
      builder.getOutputStream().close(); 
      builder.getInputStream().close(); 
      builder.getErrorStream().close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     builder.destroy(); 
     Util.println(""); 
     Util.println("Build aborted by user.", true); 

當我試圖停止該過程時,我得到以下打印。

構建由用戶中止。

已完成的建築物項目。

輸入端

我從來沒有得到「錯誤結束」和調試程序顯示了線程只是坐在「的readLine()」。

等待進程的代碼運行在它自己的線程中(與殺死進程的代碼分開)。

我需要做些什麼來確保errorPrinter線程死亡?

+0

如果在調用destroy之前不關閉流,會發生什麼? – assylias

+1

什麼是所有空的catch塊?你知道這不僅僅是壞代碼,它是徹頭徹尾的**危險**代碼。 –

+0

如果我之前沒有在流上關閉,則會發生完全相同的情況。 如果我不在乎它是否停止,爲什麼空的catch塊危險? – EmbMicro

回答

0

我有同樣的問題,我使用的是speechRecognizer,所以我運行一個單獨的線程其運行的另一個的.jar它打印到控制檯和使用的BufferedReader讀取輸出(是這樣的..):

//In seperate Thread from the Main App Thread 
while (!stopped) { 
       while ((line = bufferedReader.readLine()) != null && !line.isEmpty()) { 
        System.out.println(line); 
        checkSpeechResult(line); 
       } 
      } 

問題

基本上bufferedRead.readLine()滯後,直到它有東西可以讀。

如果什麼都沒有來,它會永遠等待。

答:

另一個線程調用此:

process.destroy(); 

,它會停止該進程使bufferedRead.readLine()將退出。