What is the difference between synchronized and volatile?

Copyright: Reprinted please note the name of the source https://blog.csdn.net/meism5/article/details/90413885

What is the difference between synchronized and volatile?

effect:

  • synchronized means that only one thread can acquire the lock object effect, execute code, blocking other threads.
  • represents a variable in the CPU volatile registers are undefined, it must be read from main memory. Ensure visibility multithreaded environment variables; prohibit instruction reordering.

 

the difference:

  • synchronized can act on variables, methods, classes; volatile can only act on variables.
  • synchronized ordering guarantees (guarantees orderly guess is not within the thread, i.e., the code within the thread may be reordered CPU instructions) between the threads, and visibility atoms; volatile only ensure the visibility and orderliness We can not guarantee atomicity.
  • synchronized thread is blocked, volatile thread is not blocked.

Guess you like

Origin blog.csdn.net/meism5/article/details/90413885