@WebServlet(urlPattens=”/demo”, asyncSupported = true)
public class AsyncDemoServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletRespone response)
throws IOException, ServletException {
respones.setContentType(“text/html; charset=utf-8”);
PrintWriter writer = response.getWriter();
out.println(“进入Servlet时间” + new Date() + “.”);
out.flush();
//在子线程中执行业务调用,并由其负责输出响应,主线程退出
AsyncContext ctx = request.startAsync();
new Thread(new Executor(ctx)).start();
out.println("结束Servlet的时间:" + new Date() + ".");
out.flush();
}
}
public class Executor implements Runnable {
private AsyncContext ctx = null;
publiic Executor(AsyncContext ctx){
this.ctx = ctx;
}
@Override
public Void run() {
try {
Thead.sleep(10000);
//用out模拟实际业务
PrintWriter out = ctx.getWriter();
out.println("业务处理完毕的时候:" + new Date() + ".");
out.flush();
ctx.complete();
} catche(Exception ex) {
e.printStackTrace();
}
}
}