現象:
??????? Runtime.exec() 方法創建標準的輸出的管道。 當子進程,往完全緩沖區此管道寫入大量數據時,它阻止在管道上直到管道緩沖區中的數據讀取父進程。 如果父進程將永遠不會讀取標準輸出, Process.waitFor() 不返回。
1、程序代碼
????? StringBuffer command = new StringBuffer();
???? ?command .append("你需要的命令行");
????? Runtime rt = Runtime.getRuntime();
????? Process process=rt.exec(command.toString());
????? int pflag = -1;
????? //重要,解決死鎖的方案
??????new PrintStream(process.getInputStream()).start();
????? pflag=process.waitFor();
????? if(pflag!=-1){
???????System.out.println("執行成功!");
?????}
???? 類PrintStream,網上找的,主要是打印信息
??? class PrintStream extends Thread{
??? ?java.io.InputStream __is = null;
??? ??public PrintStream(java.io.InputStream is)??{
????? ??__is = is;
???? ?}
???? public void run()?{
????? ?try??{
?????? while(this != null)?{
????? ?int _ch = __is.read();
?????if(_ch != -1)
??????System.out.print((char)_ch);
?????else break;
????}
???}
???catch (Exception e)
???{
????e.printStackTrace();
???}
??}
?}
2、解決方案
????? 若要避免阻止,請確保父進程始終讀取標準輸出從子進程。
posted on 2009-01-04 16:38
蔣家狂潮 閱讀(662)
評論(0) 編輯 收藏 所屬分類:
Basic