java 执行比较耗时的 shell 命令的时候常常会遇到死锁,卡死咋在程序中,具体原因我还不知道,但网上有解决方案了,亲测有用!
import java.io.*;
/**
* 描述:进程工具(防止死锁)
*
* @author: Adobe Chow
* @date: 2019/6/26 17:26
* @Copyright: www.winshang.com Inc. All rights reserved.
*/
public class ProcessUtils {
/**
* 执行命令
* @param cmd
* @throws IOException
*/
public static void exec(String cmd) throws IOException, InterruptedException {
long startTime = System.currentTimeMillis();
System.out.println("开始执行shell命令");
Process process = Runtime.getRuntime().exec(cmd);
ProcessUtils.printMessage(process.getInputStream());
ProcessUtils.printMessage(process.getErrorStream());
if (process.waitFor()==0){
System.out.println("命令执行成功(总耗时:"+(System.currentTimeMillis()-startTime)/1000+"秒)");
}else {
System.err.println("命令执行成功失败");
}
}
/**
* 读取流到控制台(防止死锁)
* @param input
*/
private static void printMessage(final InputStream input) {
new Thread(new Runnable(){
@Override
public void run() {
Reader reader = new InputStreamReader(input);
BufferedReader bf = new BufferedReader(reader);
String line = null;
try{
while((line=bf.readLine())!=null){
System.out.println(line);
}
}
catch(IOException e){
e.printStackTrace();
}finally {
try {
input.close();
} catch (IOException e) {}
}
}}).start();
}
}