【发布时间】:2011-03-26 17:02:01
【问题描述】:
即使不涉及“检查并执行”操作,也可能发生争用情况,例如,在以下代码中,十个请求将导致十个线程,但此后计数器不保证为 10。首先我说的对吗?
private int numPageHits;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
//this method executes whenever the servlet is hit
//increment numPageHits
numPageHits++;
}
一种解决方案是使用同步块,例如:
synchronize(this) {
numPageHits++;
}
我只是想知道是否有其他方法可以处理这种情况?
谢谢
【问题讨论】: