如何在servlet中运行不同的线程?

Mun*_*yar 1 java multithreading servlets

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

FileThread myThread = new FileThread();
myThread.start();
myThread.run();     
Run Code Online (Sandbox Code Playgroud)

FileThread应该看到一些文件夹来检查文件是否被更改.所以这个线程在循环中运行.但它不像我预期的那样有效.它冻结(服务器不返回HTML)服务器的服务.

我希望这个线程在后台运行,而不是干扰servlet的进程.我怎么能得到这个?

Bru*_*eis 6

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

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


Era*_*dan 5

Starting your own threads might be not the most recommended thing in a web environment, and in a Java EE one, it's actually against the spec.

Servlet 3.0 have Async support, see more here

For example

@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");
   }
}
Run Code Online (Sandbox Code Playgroud)

Java EE 6 and 7 has @Asyncronous method invocations

And Java EE 7 has Concurrency Utilities (managed Executor service for example that you can use to submit tasks to)