Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Servlet-自定义类必须是线程安全的?_Java_Multithreading_Servlets - Fatal编程技术网

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

Java Servlet-自定义类必须是线程安全的?,java,multithreading,servlets,Java,Multithreading,Servlets,如果我有一个自定义类,里面有一个静态变量,我想这个静态变量将在所有请求线程之间共享,对吗?所以我想这是我的职责,控制对变量的访问,以获得所需的行为 在下面的示例中,静态变量值是否将在所有请求线程之间共享? 我能保证来自myCustom.getValue()的结果始终为零吗?我相信没有 你说得对。static字段属于类,而不是实例。如果任何其他线程(或您当前的线程)正在调用(或已经调用)add或dec,它们在该静态字段上运行,那么您将无法保证返回0的初始值 public class MyServl

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

在下面的示例中,静态变量值是否将在所有请求线程之间共享? 我能保证来自
myCustom.getValue()
的结果始终为零吗?我相信没有


你说得对。
static
字段属于类,而不是实例。如果任何其他线程(或您当前的线程)正在调用(或已经调用)
add
dec
,它们在该
静态
字段上运行,那么您将无法保证返回
0
的初始值

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;
  }
}