How can I access static variable from many thread simultaneously.
If I have a class like
Class A {
public static boolean FLG=false;
.....................
....................
}
And I need to access the value from thread 1 like
....................
public void run() {
boolean t1=A.FLG;
..................
}
and from thread 2 I need to set value like
....................
public void run() {
A.FLG=true;
..................
}
Does this cause memory violation ?. If so what is the recommended method to handle such a situation?.
解决方案
Wrap the static variable in a synchronized method and call the method as you like
public static synchronized void method1(){
//Whatever
}
public static synchronized void method2(){
//Whatever again
}
Note that there are other ways to synchronize access to a method. They are considered more efficient in environments busy threads accessing the same methods.
Check the ReentrantLock class. There are also answers for when to use synchronized and RentrantLock and many more information that could be found through google.
Also as peter's answer and muel's comment suggests. Marking the boolean variable as volatile should be helpful. volatile boolean variables will NOT cache it's initial value (false or true). The JVM could do that occasionally which could be unexpected by the programmer.