java servlet 3.0 第三节(异步调用)示例

1   

    通过 request 对象取得 AsyncContext 

    这个是servlet和线程共享 的上下文

 

       AsyncContext asyncContext=request.startAsync();

 

2 新增 对应的线程处理类

 

 

public class MyTest implements Runnable
{
	AsyncContext asyncContext;

	public MyTest(AsyncContext asyncContext){
		this.asyncContext=asyncContext;
	}
	
	
	@Override
	public void run()
	{
		
		 try
		{
                  //通过共有上下文取得 输出对象流
                   PrintWriter writer= asyncContext.getResponse().getWriter();
			
			writer.write(" abcdef");
			
			writer.flush();
			
			Thread.sleep(15000);
			
			writer.write("ghimlno");
			
			writer.flush();
                      //调用次方法,通知线程处理结束 
                       asyncContext.complete();
		}catch (IOException e)
		{
			e.printStackTrace();
		}catch (InterruptedException e)
		{
			e.printStackTrace();
		}finally{
			
		}

	}

}
 

 

3 在 serlvet 中启动自建的线程类

 

              
                response.getWriter().write("asdfasdf");



               AsyncContext asyncContext=request.startAsync();

		new Thread(new MyTest(asyncContext)).start();
 

 

你可能感兴趣的:(servlet)