Volatile is a variable modifier, and synchronized is a modifier of a method or block. So we use both of these keywords to specify three simple ways to access variables.
int i1; int Geti1 () {return i1;}
volatile int i2; int Geti2 () {return i2;}
int i3; synchronized int Geti3 () {return i3;}
============= about the difference between the two ===================
The 1.volatile is essentially telling the JVM that the current variable's value in the register (working memory) is indeterminate and needs to be read from main memory, synchronized is the current variable, and other threads are blocked if the line can access the variable.
2.volatile can only be used at variable levels; Synchronized can be used at variable, method, and class level
3.volatile can only realize the modified visibility of variables, not guarantee atomicity, and synchronized can guarantee the modification of variables visibility and atomicity
4.volatile does not cause a thread to block; synchronized can cause threads to block.
5.volatile-tagged variables are not optimized by the compiler; synchronized-tagged variables can be optimized by the compiler
The red font part is for the following reasons:
Thread A modifies the variable before it is finished, and another thread B can see the modified value and can modify the variable without waiting for a to release the lock because the volatile variable is not locked