java 执行cmd / shell 命令 防止 死锁 封装

10 篇文章 0 订阅
6 篇文章 0 订阅

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();

    }

}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值