每个线程访问自己的数据,没有冲突
多个线程同时修改这样的数据,有冲突
案例代码如下:
package web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UpServlet extends HttpServlet { private static final long serialVersionUID = 1L; //成员变量 double salary = 2000; @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //加锁 synchronized(this){ salary += 100; //模拟网络 try { Thread.sleep(6000); } catch (InterruptedException e) { e.printStackTrace(); } //显示数据,输出给浏览器 res.setContentType("text/html;charset=utf-8"); PrintWriter out = res.getWriter(); out.println(salary); out.close(); } } } 总结:用不同的浏览器访问后得到的结果不同,如不加锁,则可能造成相同的结果