Volatile is a field modifier, while synchronized modifies code blocks and methods.
也就是说volatile只能修饰变量 synchronized只能修饰方法
When we use the regular variable
geti1() accesses the value currently stored in i1 in the current thread.(there are many thread for a single variable, because each thread has its own copy of the variable and they don’t have to be the same, because some might modify the variable, but the main memory will always have the correct value of this variable)
When we use the volatile variable
That keyword volatile makes the data in current thread synchronized across all threads, so that means it has the data the same as the correct data in the main memory. So in a sentence, that volatile variable have a higher access and update overhead that “plain variables”
The key word synchronized: it will force only one thread at a time to execute a code block. And in the same time, it synchronized every thread to the main memory.
就是说volatile只管自己这个线程和主内存的信息同步。
synchronized会把所有的线程都同步(因为毕竟不是修饰某个变量啊!)