这里参阅了网络上一段著名的对Servlet线程安全性进行测试的代码(http://zwchen.iteye.com/blog/91088)。运行之后,我们可以看一下这个例子的输出:


package p.test.servlet.threadSecurity;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(asyncSupported = true, urlPatterns = { "/threadSafeTestServlet" })
public class ThreadSafeTestServlet extends HttpServlet {

	private static final long serialVersionUID = -5360278358684235455L;
	// 定义一个实例变量,并非一个线程安全的变量
	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 {
		// 输出当前Servlet的信息以及当前线程的信息
		System.out.println(this + ":" + Thread.currentThread()
				+ " Startttttttttttttttttttttt");
		// 循环,并增加实例变量counter的值
		for (int i = 0; i < 5; i++) {
			System.out.println(this + ":" + Thread.currentThread()
					+ "Counter = " + counter);
			try {
				Thread.sleep(20000);
				counter++;
			} catch (InterruptedException exc) {
			}
		}

		System.out.println(this + ":" + Thread.currentThread()
				+ " Enddddddddddddddddddddddddd");

//		resp.getWriter().println(
//				this + ":" + Thread.currentThread()
//						+ " Enddddddddddddddddddddddddd");
//		resp.getWriter().println("Done");
//		resp.getWriter().flush();
//		resp.getWriter().close();

	}
}



sample.SimpleServlet@11e1bbf:Thread[http-8081-Processor23,5,main] 
Counter = 60 
Counter = 61 
Counter = 62 
Counter = 65 
Counter = 68 
Counter = 71 
Counter = 74 
Counter = 77 
Counter = 80 
Counter = 83 


sample.SimpleServlet@11e1bbf:Thread[http-8081-Processor22,5,main] 
Counter = 61 
Counter = 63 
Counter = 66 
Counter = 69 
Counter = 72 
Counter = 75 
Counter = 78 
Counter = 81 
Counter = 84 
Counter = 87 


sample.SimpleServlet@11e1bbf:Thread[http-8081-Processor24,5,main] 
Counter = 61 
Counter = 64 
Counter = 67 
Counter = 70 
Counter = 73 
Counter = 76 
Counter = 79 
Counter = 82 
Counter = 85 
Counter = 88

Tomcat 3.0, 默认的状态下,没有大量请求时,并发数好像是 50,

更大量的请求到来时,默认的并发数好像可以自动增加到 300,

但在这里,像这样如果命名一个 类变量 counter,肯定不是线程安全的,



Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐