Static variables and multithreading in java

后端 未结 7 1734
心在旅途
心在旅途 2020-12-02 13:31

Is a static member of a class present as only a single instance per process or thread? Meaning does each thread has its own copy of the static member variable of the class?

7条回答
  •  忘掉有多难
    2020-12-02 14:06

    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html

    Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.

    Threads have no bearing on this. (The classloader on the other hand does. If you're using multiple classloaders in your application, however, you are probably at a point where you understand that).

提交回复
热议问题