public class ConcurrentTest extends HttpServlet { PrintWriter output; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username; response.setContentType("text/html;charset=gb2312"); username=request.getParameter("Username"); output=response.getWriter(); try { //为了突出并发问题,在这设置一个延时 Thread.sleep(5000); output.println("用户名:"+username+"<BR>"); } catch (Exception e) { e.printStackTrace(); } } }部署在tomcat7上
public class SimpleServlet extends HttpServlet{ // A variable that is NOT thread-safe! private int counter = 0; public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().println("<HTML><BODY>"); resp.getWriter().println(this + " ==> "); resp.getWriter().println(Thread.currentThread() + ": <br>"); for (int c = 0; c < 10; c++){ resp.getWriter().println("Counter = " + counter + "<BR>"); try { Thread.sleep((long) Math.random() * 1000); counter++; } catch (InterruptedException exc){} } resp.getWriter().println("</BODY></HTML>"); } }和第一个例子似乎差不多,只是变量由PrintWriter变成了int。
<HTML> <BODY> <TABLE> <TR> <TD><IFRAME src="./SimpleServlet" name="servlet1" height="200%"> </IFRAME></TD> </TR> <TR> <TD><IFRAME src="./SimpleServlet" name="servlet2" height="200%"> </IFRAME></TD> </TR> <TR> <TD><IFRAME src="./SimpleServlet" name="servlet3" height="200%"> </IFRAME></TD> </TR> </TABLE> </BODY> </HTML>在tomcat7下 结果是
参考资料
两个例子分别来自下面两个地址 详细信息大家自己去看看吧
原文地址:http://blog.csdn.net/dlf123321/article/details/42369817