zoukankan      html  css  js  c++  java
  • Runtime.getRuntime().exec 类 防止阻塞


    import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.log4j.Logger; import org.richinfo.gather.driver.MainEntry; //用两个线程来分别获取标准输出流和错误输出流,否则会造成io阻塞导致程序卡死 public class ShellExec { public static String execute(String cmd) throws IOException, InterruptedException { StringBuffer sb = new StringBuffer(); final Process p = Runtime.getRuntime().exec(cmd); /*为"错误输出流"单独开一个线程读取之,否则会造成标准输出流的阻塞*/ Thread t=new Thread(new InputStreamRunnable(p.getErrorStream(),"ErrorStream")); t.start(); BufferedReader reader = null; InputStream output = p.getInputStream(); //InputStream error = p.getErrorStream(); String line = ""; reader = new BufferedReader(new InputStreamReader(output)); while ((line = reader.readLine())!= null) { sb.append(line + " "); } p.waitFor(); // if (0x00 == sb.length()) { // reader = new BufferedReader(new InputStreamReader(error)); // // while ((line = reader.readLine())!= null) { // sb.append(line + " "); // } // } reader.close(); p.destroy(); return sb.toString(); } } /**读取InputStream的线程*/ class InputStreamRunnable implements Runnable { BufferedReader bReader=null; String type=null; public InputStreamRunnable(InputStream is, String _type) { try { bReader=new BufferedReader(new InputStreamReader(new BufferedInputStream(is),"UTF-8")); type=_type; } catch(Exception ex) { } } public void run() { String line; int lineNum=0; try { while((line=bReader.readLine())!=null) { lineNum++; //Thread.sleep(200); } bReader.close(); } catch(Exception ex) { } } }

      

  • 相关阅读:
    SpringCloud 学习之概述
    定位慢查询
    中止线程
    笨办法41学会说面向对象【pyinstaller安装使用
    pip安装
    笨办法40模块, 类和对象class
    笨办法39字典dict
    笨办法38列表操作
    笨办法35分支和函数
    笨办法34访问列表元素(列表方法)
  • 原文地址:https://www.cnblogs.com/hrx-star/p/6645759.html
Copyright © 2011-2022 走看看