1,volatile
The variable it modifies does not retain a copy and accesses directly in the main memory.
In the Java memory model, there is main memory, and each thread has its own memory (for example, registers). For performance, a thread keeps a copy of the variable to be accessed in its own memory. This will show the same variable at some point, the value in the memory of one thread may be inconsistent with the value in the memory of another thread, or the value in main memory. A variable declared as volatile means that the variable is ready to be modified by another thread, so it cannot be cache in thread memory.
2,synchronized
When it is used to modify a method or a block of code, it is possible to ensure that at most one thread at a time executes that segment of code.
First, when two concurrent threads access the synchronized (this) synchronized code block in the same object objects, only one thread can be executed at a time. Another thread must wait until the current thread finishes executing the code block before executing the code block.
Second, however, when a thread accesses a synchronized (this) synchronization code block of object, another thread can still access a non-synchronized (this) synchronized code block in that object.
Third, it is particularly critical that when a thread accesses a synchronized (this) synchronization code block of object, access to all other synchronized (this) synchronized code blocks in object is blocked by other threads.
When a thread accesses a synchronized (this) synchronization code block of object, it obtains the object lock of the objects. As a result, access to all of the synchronization code portions of the object object by other threads is temporarily blocked.
The above rules apply to other object locks as well.
Difference:
One, volatile is a variable modifier, and synchronized acts on a piece of code or method.
Second, the volatile only synchronizes the value of a variable between the thread memory and the "main" memory, while synchronized synchronizes the values of all the variables by locking and unlocking a monitor. Obviously synchronized consumes more resources than volatile.