1

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

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

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

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

4

2 回答 2

6

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

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

于 2013-06-25T01:36:39.613 回答
5

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

Servlet 3.0 具有异步支持,请在此处查看更多信息

例如

@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 具有并发实用程序(例如托管的执行器服务,您可以使用它来提交任务)

于 2013-06-25T01:41:32.887 回答