小弟最近在做一个活儿,用到了线程组,遇到一个问题:
线程组中的线程已经运行结束,但是threadGroup.activeCount()仍然不为0,
这是为何呢?
另:有没有更好的方法去控制线程组中所有线程的进度,待到所有线程全部结束后再继续执行下面的代码?
貌似这种while(true)的方法挺耗费性能的····大致代码如下://线程组启动
                List<DBCursor> dbCursorList= getMongoData(request);
ThreadGroup threadGroup=new ThreadGroup("DataProcess");
MyStore.gbids.clear();

for (DBCursor dbCursor : dbCursorList) {
Thread thread=new Thread(threadGroup, new DataProcessThread(request,dbCursor));
thread.start();
}
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(threadGroup.activeCount()==0){
threadGroup.destroy();
break;
}
}//线程中的执行 public void run() {
Set<Long> gbids = dataProcessingStepOne(request,cursor);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(gbids != null){
myStore.addGBids(gbids);
}               System.out.println("~~~~~~~Thread is end~~~~~~~~~~~~~");
}

解决方案 »

  1.   

    end:threadGroup.interrupt();
      

  2.   

    threadGroup.activeCount()本身是不可靠的,只是一个估计值,不宜作为判断标准。
    用wait notify比while(true)性能要好
      

  3.   

    while(true)用起来比较简单 效率上肯定没有手动的wait notify快
    看你的具体实现了 如果线程的等待比起业务消费不了多长时间的话 可以忽略
      

  4.   

    判断一个线程是否执行完 你自己加个boolean 属性标示值就行了
    当线程执行到最后一步 赋个值标示下就行了在执行其他代码前 先判断所有线程的标示值是否完成  没完成就继续sleep
      

  5.   

    threadGroup.interrupt(); 不能作为打断线程执行的依据
    上面2位不要误导人
    threadGroup.interrupt();方法调用了每个组内线程的interrupt()方法,仅仅适用于打断处于wait()的线程
    如果是一般的while(true)循环的线程interrupt()方法无能为力一般判断循环线程的执行情况,可以加个标识public class MyThread extends Thread {
     private static final FLAG_INIT = 1;
     private static final FLAG_RUN = 2;
     private static final FLAG_OVER = 3; private int flag = 0;
     
     public MyThread() {
      flag = FLAG_INIT;
     }
     public void run() {
      flag = FLAG_RUN;  while(flag == FLAG_RUN) {
       // do something in thread
      }  flag = FLAG_OVER;
     } public void stop() {
      flag = 0;
     } public boolean isOver() {
      return flag == FLAG_OVER;
     }
    }类似这样,需要中断执行的话调用stop()方法
    判断线程是不是已经结束,看isOver()的返回