Thread - three characteristics atomicity, visibility, orderly

Atomicity , visibility , order of

What is atomicity

I.e., a plurality of operation or operations either all performed and the process will not be interrupted to perform any factor, or it is not performed.

A classic example is the bank account transfer problem:
for example, from the account transfer A to account B 1000 yuan, it must include two actions: A minus 1000 yuan from the account, to account B plus 1,000 yuan. These two operations must have the atomicity to ensure that there is some unexpected problems.

We also true operational data, such as i = i + 1; including the read value of i, i is calculated, written i. This line of code in Java is not available atomic, then there will be problems running multi-threaded, so we also need to use synchronization and lock these things to make sure that this feature of.

In fact, atomicity is to ensure data consistency, thread safety part,

What is the visibility

When multiple threads access the same variable, a thread changes the value of this variable, other threads can immediately see the modified values.

If two threads in different cpu, then thread 1 changes the value of i did not modify the thread to refresh main memory, thread 2 and i use, it is still before the affirmation of the value of i, the thread 1 of the variables did not see this is the visibility of the problem.

What is orderly

The program execution sequence performed in the order code.

In general processor in order to improve process efficiency, might enter the code optimization, it does not ensure the implementation of the program in individual statements in the order consistent with the order of the code, but it will ensure that the final program execution and results of the code sequence the result is the same. as follows:

int a = 10; // statement 1

int r = 2; // statement 2

a = a + 3; // statement 3

r = a * a; // statement 4

Because the reordering, he might order of execution is 2-1-3-4,1-3-2-4
but not likely 2-1-4-3, because it breaks the dependency.
Obviously reorder single thread is not going to have any problems, but not necessarily multi-threaded, so we have to consider this issue at the time of multi-threaded programming.

Guess you like

Origin www.cnblogs.com/pickKnow/p/11023147.html