Process的的waitFor()造成的阻塞

来源:互联网 发布:网络信息安全龙头股 编辑:程序博客网 时间:2024/04/27 23:06


我们在调用Process的waitFor()时经常会遇到明明Process已经结束了,但是waitFor()还是阻塞在那里,那是因为Process的inputStream缓存造成的,我们现在另外再起一个线程,来监控我们的Process,实时清空缓存就可以解决这个问题了

class WatchThread extends Thread   { Process   p;         boolean   over;        ArrayList<String> stream;        public WatchThread(Process p) {             this.p = p;             over = false;            stream = new ArrayList<String>();        }         public void run() {           try {                if(p == null)return;                Scanner br = new Scanner(p.getInputStream());               while (true) {                    if (p==null || over) break;                    while(br.hasNextLine()){                   String tempStream = br.nextLine();                   if(tempStream.trim()==null||tempStream.trim().equals(""))continue;                   stream.add(tempStream);                   }               }                } catch(Exception   e){e.printStackTrace();}         }                public void setOver(boolean   over)   {               this.over   =   over;         }        public ArrayList<String> getStream() {        return stream;        }}


然后在waitFor之前插入

WatchThread wt = new WatchThread(p2);wt.start();


在waitFor之后插入

 

ArrayList<String> commandStream = wt.getStream();wt.setOver(true);


这样,即清空了inputStream,又不会造成需要的人无法获取inputStream的信息,waitFor()阻塞的问题也解决了

0 0