神马 - 云代码空间
—— 任何傻瓜都能写出计算机可以理解的代码,好的程序员能写出人能读懂的代码。
package com.cndatacom.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.AsyncContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.cndatacom.thread.BusinessHandleThread; /** * 异步处理Servlet * @author Luxh */ /** * asyncSupported属性默认是false,如果需要开启支持异步处理功能,需要设置为true */ @WebServlet(name="AsyncServlet",urlPatterns="/AsyncServlet",asyncSupported=true) public class AsyncServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("Servlet begin <br>"); //进入异步模式,调用业务处理线程进行业务处理 //Servlet不会被阻塞,而是直接往下执行 //业务处理完成后的回应由AsyncContext管理 AsyncContext asyncContext = request.startAsync(); BusinessHandleThread businessHandleThread = new BusinessHandleThread(asyncContext); Thread thread = new Thread(businessHandleThread); thread.start(); //asyncContext.start(businessHandleThread);//也可以用这种方法启动异步线程 out.println("Servlet end <br>"); out.flush(); } }进行业务处理的线程:
package com.cndatacom.thread; import java.io.PrintWriter; import javax.servlet.AsyncContext; import javax.servlet.ServletResponse; /** * 业务处理线程 * @author Luxh */ public class BusinessHandleThread implements Runnable { //异步操作的上下文对象,通过构造方法传进来 private AsyncContext asyncContext; public BusinessHandleThread(AsyncContext asyncContext) { this.asyncContext =asyncContext; } @Override public void run() { try { //do some work... Thread.sleep(6000); ServletResponse response = asyncContext.getResponse(); PrintWriter out = response.getWriter(); out.println("业务处理方法执行结束");//这句话会响应到客户端 //告诉启动异步处理的Servlet异步处理已完成,Servlet就会提交请求 asyncContext.complete(); } catch (Exception e) { e.printStackTrace(); } } }AsyncContext:代表的是一个ServletRequest发起一个异步操作的执行上下文。