I have a few calculations that I'm spawning off into new threads then when all these calculations are complete I want to continue my execution.
Here's some mock up code that is similar to what I want to achieve without all the specifics,
public void calculation1(){
Thread thread = new Thread(){
public void run(){
/* do calculation */
};
};
}
public void calculation2(){
Thread thread = new Thread(){
public void run(){
/* do some other calculation */
};
};
}
calculation1();
calculation2();
/* Wait here until calculation1() and calculation2() complete */
/* Continue execution */
What's the best way for me to do this??
解决方案
Something like this:
public Thread calculation1(){
Thread thread = new Thread(){
public void run(){
/* do calculation */
}
};
thread.start();
return thread;
}
public Thread calculation2(){
Thread thread = new Thread(){
public void run(){
/* do some other calculation */
};
};
thread.start();
return thread;
}
And then use isAlive() and join() to wait for execution to finish
List threads = new ArrayList();
threads.add(calculation1());
threads.add(calculation2());
for(Thread t : threads){
if(t.isAlive()){
t.join();
}
}