Servlet - 自定义类必须是线程安全的吗?

时间:2014-12-26 18:41:13

标签: java multithreading servlets

如果我有一个自定义类,里面有一个静态变量,我想这个静态变量将在所有请求线程之间共享,对吧?所以我想我有责任控制对变量的访问以获得所需的行为。

在下面的示例中,是否会在所有请求线程之间共享静态变量值?  我可以保证myCustom.getValue()的结果总是为零吗?我不相信。

public class MyServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CustomClass myCustom = new CustomClass();
        myCustom.add();
        myCustom.dec();
        myCustom.getValue(); //
    } 
}

public class CustomClass {
  private static int value = 0;

  public void add(){
      this.value ++;
  }

  private void dec(){
      this.value --;
  }

  private int getValue(){  
      return this.value;
  }
}

1 个答案:

答案 0 :(得分:2)

你是对的。 static字段属于该类,而不属于该实例。如果任何其他线程(或您当前的线程)正在调用(或已调用)adddec,这些线程在此static字段上运行,那么您将无法保证收回0的初始值。

相关问题