我有一个 Servlet,它接收请求,必须处理 5 个任务(从外部服务器获取数据)并将所有数据发送回订购的客户端。
如何同时处理5个任务并在5个任务全部完成后继续执行servlet代码?
您可以使用CoundDownLatch http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
一种同步辅助工具,允许一个或多个线程等待,直到其他线程中执行的一组操作完成。
示例代码:
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(5); // 5 tasks
class Worker implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
private final int threadNumber;
// you can pass additional arguments as well
Worker(CountDownLatch startSignal, CountDownLatch doneSignal,
int threadNumber) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
this.threadNumber = threadNumber;
}
public void run() {
try {
startSignal.await();
doWork(); // actual work to be performed here
doneSignal.countDown();
} catch (InterruptedException ex) {
LOGGER.error(ex);
}
}
}
// 5 new threads are started
for(int i=1;i<=5;i++){
new Thread(new Worker(startSignal, doneSignal, i)).start();
}
startSignal.countDown(); // let all threads proceed
try {
doneSignal.await(); // wait for all to finish
// all 5 tasks are finished and do whatever you want to do next
} catch (InterruptedException interruptedException) {
LOGGER.error(interruptedException);
}
阅读更多... https://stackoverflow.com/questions/17827022/what-is-countdown-latch-in-java-multithreading and 查找更多示例... http://www.javacodegeeks.com/2011/09/java-concurrency-tutorial.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)