Java – 等待第三方线程完成

我有一个运行第三方库的线程,它也将运行自己的线程.当我的线程的run方法完成时,第三方线程将不会完成.

那么,在这些外部线程仍在运行之前,保持我的线程的最佳方法是什么?

解决方法

如果您是一个应用程序而不必担心SecurityManager限制,并且如果您准备在更新第三方代码时偶尔修改代码,则可以使用ThreadGroup的工具来遍历线程并通过以下方式识别它们:名称或包含它们的线程组.

一旦找到了线程,就可以在它们完成之前监视它们,或者在适当的时候使用Thread.join().

举个例子,这里有一些工作代码转储JVM中的所有线程:

public void printThreads(PrintWriter wtr) {
    ThreadGroup     root;

    totGroups=0;
    totthreads=0;

    for(root=Thread.currentThread().getThreadGroup(); root.getParent()!=null; root=root.getParent()) {}
    wtr.println("Thread Dump:");
    printThreadGroup(wtr,root,"  ");
    wtr.println("  -- Total Groups: "+totGroups+",Total Threads: "+totthreads);
    }

public void printThreadGroup(PrintWriter wtr,ThreadGroup grp,String pfx) {
    try {
        Thread[]        thds;
        ThreadGroup[]   grps;

        totGroups++;
        wtr.println(pfx+"Group: "+grp.getName()+","+(grp.isDaemon()?"Daemon":"normal")+","+(grp.isDestroyed()?"Destroyed":"Alive")+","+grp.getMaxPriority());
        thds=new Thread[grp.activeCount()];
        grp.enumerate(thds,false);
        Arrays.sort(thds,THREAD_SORTER);
        for(int xa=0; xa<thds.length && thds[xa]!=null; xa++,totthreads++) {
            Thread          thd=thds[xa];
            wtr.println(pfx+". - ["+thd.getName()+","+(thd.isDaemon()?"Daemon":"normal")+","+(thd.isAlive()?"Alive":"Not Started or Dead")+","+thd.getPriority()+"]");
            }

        grps=new ThreadGroup[grp.activeGroupCount()];
        grp.enumerate(grps,false);
        Arrays.sort(grps,GROUP_SORTER);
        for(int xa=0; xa<grps.length && grps[xa]!=null; xa++) {
            printThreadGroup(wtr,grps[xa],(pfx+". "));
            grps[xa]=null;
            }
        }
    catch(Throwable thr) {
        wtr.println("  Cannot print threads ("+thr+")");
        }
    }

public void printStacks(PrintWriter wtr) {
    wtr.println("Thread Stack Traces:");
    try { javaMx.printStacks(wtr); } catch(Throwable thr) { wtr.println("  Cannot print stacks ("+thr+")"); }
    wtr.println("  --");
    }

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...