我有一个 Servlet,它接收请求,必须处理 5 个任务(从外部服务器获取数据)并将所有数据发送回订购的客户端。
如何同时处理 5 个任务并在 5 个任务全部完成后继续执行 servlet 代码?
最佳答案
您可以使用CoundDownLatch
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
示例代码:
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);
}
关于java - 在一个 Servlet 中同时处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24981726/