starting many thread problem
Hi,
In a for statement I want to start one thread for each element of the collection I'm iterating over, however I don't want them to actually run before the iteration is done.. That's what I'm doing now :
for (X x: listOfX){
Thread thread =new Thread(x);
thread.start();
}
Of course, X implements Runnable.
Thanks for help.
[497 byte] By [
JF_La] at [2007-11-26 18:50:30]

# 1
You can't control when the started threads actually start running.
What you can do is put some synchronization code in the Runnable to make sure no thread gets past a certain point until the main threads signals that the iteration is complete. You can use a CountdownLatch for this:
final CountDownLatch startSignal = new CountDownLatch(1);
// in the Runnable
public void run() {
try {
startSignal.await();
} catch (InterruptedException ex) {
// choose how to respond eg return or throw Error
}
// real work of the Runnable
}
// main thread
for (X x: listOfX) {
Thread thread = new Thread(x);
thread.start();
}
startSignal.countDown(); // release all the started threads
Of course there is still no guarantee about the ordering - but no thread passes the latch until the main thread says it is okay.