Volatile: Only guarantee the visibility of shared resources, any changes are written in main memory, all threads can be seen immediately, for the new value does not depend on the old value of the case.
Synchronized: Ensures operational atomicity consistency and visibility.
The difference between volatile and synchronized:
Volatile only causes variables to be known to other threads as soon as the value changes, and does not guarantee the sequential execution of multithreading. Instead, synchronized locks the current variable, and other threads are blocked only if the variable is accessible to the front thread.
Volatile can only implement variable visibility but does not have atomic properties, while synchronized can guarantee the change visibility and atomicity of variables.
Volatile does not cause a thread to block, and synchronized can cause a thread to block.
Volatile tagged variables are not optimized by the compiler, and synchronized tagged variables can be optimized by the compiler.
Appendix:
1. When a thread enters the synchronized method of an instance of an object, no other thread can access the method, but it can access the non-synchronous method of the object at the same time
2,the difference between Lock and synchronized--lock must be released after use, usually released in the finally block. Otherwise, if the protected code throws an exception, the lock may never be released.
Java re-learning--synchronized and volatile