java - 在一个 Servlet 中同时处理

标签 java multithreading servlets asynchronous

我有一个 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);
    }

Read more...Find more examples...

关于java - 在一个 Servlet 中同时处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24981726/

相关文章:

java - 通过添加配置文件更改 Vert.x 中的日志级别

java - 安卓 : Does accessing view in nested layout takes time?

java - 是否多线程任务?

java - 如何使用 JAVA EE 获取用于下载文件的 HttpServletResponse 实例

java - 如何禁用 Servlet 3.0 扫描和自动加载组件

java - java中的过程调用抛出异常

java - Hibernate可以保留哪些类型的类?

java - 如何使用 C++ 打开 Java 程序

python - dask distributed 是否使用 Tornado 协程来处理 worker 任务?

java - 多线程中如何处理OutOfMemoryError?