Threads wait until all threads return output using java? [duplicate]
Possible Duplicate:
How to wait for a set of threads to complete?
I want to run three threads, each thread calls different classes. These classes do some processing and return a Boolean
value, I wa开发者_StackOverflownt to wait until all three threads return their output. I want to know how it's possible to implement this using Java.
Thanks
You can use Thread.join()
to do that:
Thread[] threads = new Thread[numOfThreads];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
public void run() {
System.out.println("xxx");
}
});
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
}
}
For your solution
Thread[] threads = new Thread[3];
threads[i] = new Thread(new Runnable() {
...
}).start();
threads[i] = new Thread(new Runnable() {
...
}).start();
threads[i] = new Thread(new Runnable() {
...
}).start();
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
}
}
If you are using an ExecutorService you can do
ExecutorService es = /* create a reusable thread pool */
List<Future> futures = new ArrayList<Future>();
futures.add(es.submit(myRunnable1));
futures.add(es.submit(myRunnable2));
futures.add(es.submit(myRunnable3));
for(Future f: futures) f.get(); // wait for them to finish.
If you want to return a boolean, you should use a Callable instead. You can also use invokeAll
ExecutorService es = /* create a reusable thread pool */
List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
es.invokeAll(Arrays.asList(
new Callable<Boolean>() {
public Boolean call() {
return true;
}
},
new Callable<Boolean>() {
public Boolean call() {
return false;
}
},
new Callable<Boolean>() {
public Boolean call() {
return true;
}
}
));
for(Future<Boolean> f: futures) {
Boolean result = f.get();
}
A thread has a join
method. If your main thread calls that method on a thread t
, the main thread will wait until t
has finished.
See http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#join()
You can use a "barrier" (see CyclicBarrier for an implementation in the Java API). Alternatively, if you just want to get the output, but don't need them all to finish before handling the output, you could represent your computations using Future which will block if needed when getting the result.
You may use Thread.join() as the following: -
Thread t1 = new Thread(myRunnable1);
Thread t2 = new Thread(myRunnable2);
Thread t3 = new Thread(myRunnable3);
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
//do something when all 3 threads finish
I hope this may help to achieve your requirement.
Regards,
Charlee Ch.
Please take a look at the examples in ExecutorCompletionService
精彩评论