try something like this:
1. keep a thread count, when you create a new thread, increment the count (needs synchronized)
2. pass into the new thread an instance of an interface the main thread implements
3. When the new thread ends, it will call some function in that inteface. In this function, the thread count (needs synchronized) will be decremented. When the count becomes 0, it will notify the main thread, then you can terminate the main thread
1. keep a thread count, when you create a new thread, increment the count (needs synchronized)
2. pass into the new thread an instance of an interface the main thread implements
3. When the new thread ends, it will call some function in that inteface. In this function, the thread count (needs synchronized) will be decremented. When the count becomes 0, it will notify the main thread, then you can terminate the main thread
产生了几个(有没有超生游击队),并且不能退出去,而要等在那儿,你可
可以用Object.wait()每个工作线程在结束之前,要通知主线程,可以用
Object.notify()/Object.notifyAll()主线程被唤醒后,要计算/判断当前活着的工作线程数,若为0则
退出,否则继续Object.wait()
以上未考虑notify失效等问题,不是很实用,每个工作线程在退出
前,可和主线程多次通信,确保counter被剪过再退出:要不然不是
白牺牲了吗?哈哈哈哈哈
static byte[] counterLocker = new byte[0]; //a locker
static int counter; mainDo(){
//make new Thread;
counter++; while (counter>0) {
synchronized(counterLocker){
counterLocker.wait();
counter--;
}
}
}}
working Thread 大概是这样的:
public void run(){
//... mainThread.counterLocker.notify();}
}大概是这样的
每个子线程退出时把该变量减1;当该变量减到0时,通知主线程,然后主线程退出。
我的程序中有这样的方法:每创建一个新的线程时,把自己加入一个vector中,退出时就把自己从vector中移出。因为我的程序没有必要在vector为空时退出,不过我想你可以开出一个新的线程来监视vector是否为空,不用循环,因为是vector,对吧,其实与你的想法差不多。在我的程序中只是要主线程结束时,让每个线程都能释放所点用的资源。