测试servlet线程安全问题
1.新建一个servletThread的类代码如下:
package eduask;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Servlet线程安全问题;
public class ServletThread extends HttpServlet{
//定义一个全局变量;
int i=0;
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
synchronized (this) {
try {
i++;
Thread.sleep(1000);
System.out.println("这是第"+i+"次访问");
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
2.配置web.xml,配置结果如下:
<!-- 测试servlet线程问题 -->
<servlet>
<servlet-name>servletThread</servlet-name>
<servlet-class>eduask.ServletThread</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletThread</servlet-name>
<url-pattern>/servletThread</url-pattern>
</servlet-mapping>
3.启动tomcat,在浏览器中输入:
http://localhost:8080/webDemo/servletThread
4.重复刷新5次,则会在控制台显示你已经访问了6次