process阻塞

本文介绍了一种改进的等待方法,用于解决Java主进程在调用子进程后立即继续执行的问题,避免了传统方法可能导致的阻塞情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 调用系统其他进程,未等被启动进程进行完,java主进程就继续往下执行了,本以为调用procc.waitfor()可以解决问题,未果,google之发现如下方法:

代码:

//对process.waitFor()的改造,被启动的进程会因为缓冲区不够而被阻塞无法启动,调用该方法可以成功
public static int doWaitFor(Process p) { 
int exitValue = -1; // returned to caller when p is finished 
try { 
InputStream in = p.getInputStream(); 
InputStream err = p.getErrorStream(); 
boolean finished = false; // Set to true when p is finished 
while(!finished) { 
try { 
while( in.available() > 0) { 
// Print the output of our system call 
Character c = new Character( (char) in.read()); 
System.out.print( c); 
} 
while( err.available() > 0) { 
// Print the output of our system call 
Character c = new Character( (char) err.read()); 
System.out.print( c); 
} 
// Ask the process for its exitValue. If the process 
// is not finished, an IllegalThreadStateException 
// is thrown. If it is finished, we fall through and 
// the variable finished is set to true. 
exitValue = p.exitValue(); 
finished = true; 
} catch (IllegalThreadStateException e) { 
// Process is not finished yet; 
// Sleep a little to save on CPU cycles 
Thread.currentThread().sleep(500); 
} 
} 
} catch (Exception e) { 
// unexpected exception! print it out for debugging... 
System.err.println( "doWaitFor(): unexpected exception - " + 
e.getMessage()); 
} 
// return completion status to caller 
return exitValue; 
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值