> Hi,
>
[quoted text clipped - 5 lines]
> for a group of threads to finish, with a timeout limit. Is there a way other
> then keep polling the ThreadGroup's activeCount()?
I havn't used ThreadGroups and I've been told they don't work well.
Fortunately, the case you describe is easy because you are waiting for all
the threads to end, rather than just the first one. This means you're
really waiting for the longest thread. Simply join each in turn. Any
thread that's longer than the timeout will simply cause the ordinary timeout
and you can exit. Any that have already ended while you were waiting will
join in (virtually) no time at all. This just leaves those that end during
the join, but that leave some of the timeout for the next thread. The
following example keeps track of the time spent waiting and returns true if
the wait succeeds for all and false if it times out. (Any
interruptedException on the waiting thread is passed up--you may need more
complex exception handling.) Also, if the last thread ends with 0 time
remaining, that won't be considered a timeout
public static boolean waitForThreads (Set threads, long
timeoutMilleseconds)
throws InterruptedException {
long timeRemainingMS = timeoutMilleseconds;
Iterator it = threads.iterator ();
while (it.hasNext () && (timeRemainingMS > 0) ) {
Thread t = (Thread)it.next ();
long startJoin = System.currentTimeMillis ();
t.join (timeRemainingMS);
if (t.isAlive ()) return false; // Used up all the timeout
timeRemainingMS = timeRemainingMS - (System.currentTimeMillis () -
startJoin);
}
return true;
}
Cheers,
Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/
Jac - 30 Jan 2004 23:42 GMT
> > Hi,
> >
[quoted text clipped - 45 lines]
> Cheers,
> Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/
Jac - 30 Jan 2004 23:47 GMT
This is definitely a good solution. Thanks very much for your help~!!!
> > Hi,
> >
[quoted text clipped - 45 lines]
> Cheers,
> Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/