在一个Servlet的同时处理 [英] Simultaneously processing in one Servlet
问题描述
我有一个Servlet其中临危要求,具有处理5个任务(获取数据形式的外部服务器)和所有数据发送回订购的客户。
I have a Servlet which recieves a request, has to process 5 tasks (Grab data Form external Servers) and send all the data back to the client ordered.
如何同时处理5任务,并与该servlet code继续所有5个任务完成后?
How to process the 5 Task simultaneously and continue with the servlet code after all 5 tasks are completed?
推荐答案
您可以使用的 CoundDownLatch
You can use CoundDownLatch
一个同步辅助,允许一个或多个线程等待,直到其他线程中执行一组操作完成。
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
样code:
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);
}
<一个href=\"http://stackoverflow.com/questions/17827022/what-is-countdown-latch-in-java-multithreading\">Read更多... 和找到更多的例子。 ..
这篇关于在一个Servlet的同时处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!