在Web環境中啓動自己的線程可能不是最值得推薦的事情,而在Java EE中,它實際上違反了規範。
的Servlet 3.0有異步支持,看到更多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(管理執行器服務例如你可以用 來提交任務)
注意應該是在Java EE容器中產生非託管線程是一個非常糟糕的主意。從這裏開始:http://stackoverflow.com/questions/8327880/can-i-spawn-new-threads-in-jsp/8328113#8328113 – BalusC