栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

让父线程等到子线程完成或超时

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

让父线程等到子线程完成或超时

您可以执行Thread.join(long)或Thread.join(long,int)并在单独的线程中启动进程。

添加一些代码。(有效,但未在所有极端情况下进行全面测试)

  public class Test {     public static void main(String[] args) throws Throwable  {        for(int i = 0; i < 3; i++) {ProcessRunner pr = new ProcessRunner(args);pr.start();// wait for 100 mspr.join(100);// process still going on? kill it!if(!pr.isDone())  {   System.err.println("Destroying process " + pr);   pr.abort();}        }     }     static class ProcessRunner extends Thread  {        ProcessBuilder b;        Process p;        boolean done = false;        ProcessRunner(String[] args)  {super("ProcessRunner " + args); // got lazy here :Db = new ProcessBuilder(args);        }        public void run()   {try   {   p = b.start();   // Do your buffered reader and readline stuff here   // wait for the process to complete   p.waitFor();}catch(Exception e) {   System.err.println(e.getMessage());}finally {   // some cleanup pre   done = true;}        }        int exitValue() throws IllegalStateException  {if(p != null)  {   return p.exitValue();}         throw new IllegalStateException("Process not started yet");        }        boolean isDone()  {return done;        }        void abort()   {if(! isDone()) {   // do some cleanup first   p.destroy();}        }     }  }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610193.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号