Synchronization represses this caching behavior. According to the Java memory
model, a thread's local memory is reset to the values stored in main memory
when the thread acquires a lock. Furthermore, local memory values are written
back to main memory when the thread releases that lock.
Unfortunately, excessive synchronization can cause a program's performance to
suffer. To balance the need to (occasionally) avoid local memory versus not
sacrificing performance, Java provides the volatile
keyword. For
each variable marked with that keyword, Java reads that variable's value from
main memory, and writes that variable's value to main memory. Local memory is
avoided.
一句话,就是不让JVM将改变了放到CPU的缓存中,来提高性能,而每次的读写都从
内存中进行。避免不同线程之间访问统一数据时的不一致。