在应用中只有一个实例对象,但是多个线程访问一个servlet时,就会存在线程安全问题。
解决方案如下:
第一种:在方法中使用同步代码块
public class ServletDemo extends HttpServlet {
// 1-定义一个成员变量
// 多个浏览器同时访问会出现线程安全问题
private String username;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
synchronized (this) {
// 2-获取用户名
username = req.getParameter("username");
// 加这个休眠 只是为了让我们的问题暴漏的更严重
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 3-将用户响应给浏览器
PrintWriter pw = resp.getWriter();
pw.write("Welcome:" + username);
}
}
}
第二种:避开 在servlet 中定义变量
如果要使用到变量,可以定义为局部变量,这样每条线程都有自己的局部变量,就不会出现线程安全问题了
public class ServletDemo extends HttpServlet {
// 1-定义一个成员变量
// 多个浏览器同时访问会出现线程安全问题
// private String username;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 定义为局部变量
String username = null;
// 2-获取用户名
username = req.getParameter("username");
// 加这个休眠 只是为了让我们的问题暴漏的更严重
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 3-将用户响应给浏览器
PrintWriter pw = resp.getWriter();
pw.write("Welcome" + username);
}
}
总结:尽量采用第二种方案。因为第一种方案,如果访问量过大的时候,需要等候的时间太长。
希望对你有帮助哦