Andrea B. said:
In my java application i need to launch several parallel threads to
execute elementary parts of a complex calculation.
So, the main application should wait for the end of all the threads
and evaluate a general result.
I also have to notify to the main application when some thread exceed
a maximum timeout.
Could someone tell me how to implement this programming logic in Java?
I would be grateful if you could send me some sample code.
Waiting for the end of many threads is very easy as you know you have to
wait at least as long as the longest running thread. Simply join each one
in turn. If the thread has already ended, the join will return immediately.
If the thread has not, it will wait and other threads will be finishing in
the mean time. When you reach the end of the list you will not have waited
much more than the length of the longest thread.
List threads; // Say this list holds all the threads you must wait for
// When waiting for them to end
for (int i = 0; i < threads.size (); ++i) {
((Thread)threads.get(i)).join ();
}
The timeout aspect can be much more complicated, although I'm not sure what
you're asking for because you don't say what the main task will do when it
finds out the thread has exceeded its timeout. That is, does it simply want
to know to update a display, or does it want to stop the thread and possibly
start a new one or does it simply not want to wait more than X seconds for
the entire task to complete? The solutions for these are very different
and some may be simpler if we knew more about what you're trying to do.
From your description, I would guess that what you want is for each thread
to have a potentially different timeout and that you want the main task to
be able to stop an over-running thread and take some corrective action. In
one solution the main task has a monitoring thread that has a list of the
other threads and the expiration time of each one. This thread is set to
sleep until the soonest of the expiring threads is due. When a thread
finishes, it notifies the main task monitoring thread, which removes it from
the list. The monitoring thread finds the next soonest expiration time and
goes back to sleep. If the monitor thread ever wakes up on its own, it
removes the threads that were supposed to expire by invoking a custom stop
command on them, and then goes back to waiting for the next ones until there
are no more threads. Designing and coding this mechanism is not a small job
and requires some skills with Java thread synchronization and wait / notify.
Is that what you're looking for?
Cheers,
Matt Humphrey (e-mail address removed)
http://www.iviz.com/