java - Android: Waiting for the threads to finish executing the method -
executorservice exec = executors.newfixedthreadpool(8); list<future<object>> results = new arraylist<future<object>>(); // submit tasks for(int = 0; < 8; i++) { results.add(exec.submit(new threadtask())); } ... // stop pool accepting new tasks exec.shutdown(); // wait results for(future<object> result: results) { object obj = result.get(); } class threadtask implements callable<object> { public object call() { // execute download ... return result; } }
the above code doesn't show me results expected. in more detail, i'm doing download manager android. these threads downloading file in segments. since, each segment may take different time duration download, think that's problem lies.
then tried using simple number return inside method. threads started give expected results.
so solution thought of implementing method wait threads finish executing. in above code, how wait threads finish work?. think have use wait()
method have no idea how it.hope can figure out this.
thanks time.
if need set of threads meet @ point - try use "barrier" pattern.
java se has it's implementation : java.util.concurrent.cyclicbarrier
from docs : synchronization aid allows set of threads wait each other reach common barrier point. cyclicbarriers useful in programs involving fixed sized party of threads must wait each other. barrier called cyclic because can re-used after waiting threads released.
a cyclicbarrier supports optional runnable command run once per barrier point, after last thread in party arrives, before threads released. barrier action useful updating shared-state before of parties continue.
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/cyclicbarrier.html
Comments
Post a Comment