What is the difference between atomic / volatile / synchronized?

后端 未结 7 1068
长情又很酷
长情又很酷 2020-11-22 16:56

How do atomic / volatile / synchronized work internally?

What is the difference between the following code blocks?

Code 1

private int counter         


        
7条回答
  •  时光取名叫无心
    2020-11-22 17:26

    The Java volatile modifier is an example of a special mechanism to guarantee that communication happens between threads. When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about all of the contents of memory up until it performed the write to that volatile variable.

    Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.

提交回复
热议问题