【问题标题】:How to run a different thread in a servlet?如何在 servlet 中运行不同的线程?
【发布时间】:2013-06-25 01:20:27
【问题描述】:

如何从 servlet 运行不同的线程?我在 servlet 的 init() 方法中有以下代码。

FileThread myThread = new FileThread();
myThread.start();
myThread.run();     

FileThread 应该查看某个文件夹以检查文件是否已更改。所以这个线程是循环运行的。但它并没有像我预期的那样工作。它冻结(服务器不返回 HTML)服务器的服务。

我希望这个线程在后台运行并且不干扰 servlet 的进程。我怎样才能做到这一点?

【问题讨论】:

标签: java multithreading servlets


【解决方案1】:

您通常不会在Thread 上调用.run(),因为它会使run() 方法在当前线程上运行,而不是在新线程上!你说你那里有一个无限循环,因此 servlet 永远不会完成初始化,因此它不会处理任何请求!

您只需在 Thread 对象上调用 .start()。此方法将使 JVM 启动一个新的执行线程,该线程将运行该 Thread 对象的 run() 方法中的代码。

【讨论】:

  • +1 - 成功了!调用run() 意味着servlet 线程现在要“执行应由工作线程执行的活动”。
【解决方案2】:

在 Web 环境中启动自己的线程可能不是最推荐的做法,而在 Java EE 环境中,这实际上是违反规范的。

Servlet 3.0 支持 Async,查看更多 here

例如

@WebServlet("/foo" asyncSupported=true)
   public class MyServlet extends HttpServlet {
        public void doGet(HttpServletRequest req, HttpServletResponse res) {
            ...
            AsyncContext aCtx = request.startAsync(req, res);
            ScheduledThreadPoolExecutor executor = new ThreadPoolExecutor(10);
            executor.execute(new AsyncWebService(aCtx));
        }
   }

   public class AsyncWebService implements Runnable {
        AsyncContext ctx;
        public AsyncWebService(AsyncContext ctx) {
            this.ctx = ctx;
        }
        public void run() {
            // Invoke web service and save result in request attribute
            // Dispatch the request to render the result to a JSP.
            ctx.dispatch("/render.jsp");
   }
}

Java EE 6 和 7 有 @Asyncronous 方法调用

而 Java EE 7 有 Concurrency Utilities(例如,您的托管 Executor 服务) 可以用来提交任务)

【讨论】:

    猜你喜欢
    • 2015-08-08
    • 2019-08-23
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    相关资源
    最近更新 更多