Servlet asynchronous processing

@WebServlet(value = "/asycservlet",asyncSupported = true)
public class AsycServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println ( "main thread start" + Thread.currentThread () + "..." + System.currentTimeMillis ());
        AsyncContext startAsync=req.startAsync();
        startAsync.start(new Runnable(){
            @Override
            public void run() {
                System.out.println("异步程启动"+Thread.currentThread()+"..."+System.currentTimeMillis());
                try {
                asyc();
                AsyncContext asyncContext=req.getAsyncContext();
                ServletResponse response=asyncContext.getResponse();
                response.getWriter().write("asyc success");
                } catch (IOException e) {
                    e.printStackTrace ();
                }catch (InterruptedException e){
                    e.printStackTrace ();
                }finally {
                    startAsync.complete();
                }
                System.out.println("异步程结束"+Thread.currentThread()+"..."+System.currentTimeMillis());
            }
        });
        System.out.println ( "main thread end" + Thread.currentThread () + "..." + System.currentTimeMillis ());
    }

    public void asyc() throws InterruptedException{
        System.out.println(Thread.currentThread()+"......");
        Thread.sleep(5000);
    }
}

 

 

Guess you like

Origin www.cnblogs.com/qin1993/p/11934732.html