Volatile provides a weak synchronization mechanism to ensure that variable updates are notified to other threads. Volatile variables are not cached in registers or otherwise invisible to other processors, so reading a volatile variable always returns the most recently written value. It can be imagined as the following semantics, but volatile is a more lightweight synchronization mechanism. Volatile can only ensure visibility, but not atomicity. In other words, volatile variables cannot be used in composite operations, such as i++.
Copy the code code as follows:
public synchronized void setValue(int value){
this.value = value;
}
public synchronized int getValue(){
return value;
}
Volatile variables can only be used when all of the following conditions are met:
1. The write operation to the variable does not depend on the current value of the variable, or you can ensure that only a single thread updates the variable value.
2. This variable will not be included in the invariance condition along with other state variables
3. There is no need to lock when accessing variables.