現(xiàn)象:
??????? Runtime.exec() 方法創(chuàng)建標(biāo)準(zhǔn)的輸出的管道。 當(dāng)子進(jìn)程,往完全緩沖區(qū)此管道寫入大量數(shù)據(jù)時(shí),它阻止在管道上直到管道緩沖區(qū)中的數(shù)據(jù)讀取父進(jìn)程。 如果父進(jìn)程將永遠(yuǎn)不會(huì)讀取標(biāo)準(zhǔn)輸出, 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("執(zhí)行成功!");
?????}
???? 類PrintStream,網(wǎng)上找的,主要是打印信息
??? 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、解決方案
????? 若要避免阻止,請(qǐng)確保父進(jìn)程始終讀取標(biāo)準(zhǔn)輸出從子進(jìn)程。