Several characteristics of a thread of execution (sharing, mutually exclusive, atomic, visibility, ordering)

First, sharing

Multiple threads share the same memory, it can cause thread-safety issues.

A variable such as simultaneously Thread1 and Thread2 access, may occur and variables A Thread1 Thread2 reading is not the same value, and in most cases Thread1 Thread2 not be exactly the same time to read a variable A, and the variable A difference this time It may have been modified.

Second, mutually exclusive

For the same resources is concerned, the same time only one thread access. Resources to solve the inconsistency of multiple threads read and write but to pay attention to coverage of the issue.

Third, atomicity

The operation of the resources of a complete process. It will not do anything else to stop execution of the operation. The so-called atomic jvm refers to the actual implementation, rather than the code level.

For example: i ++ not atomic operation.

例如: classes ClassA = new ClassA ().

Use synchronized ensure atomicity and mutual exclusion.

Fourth, visibility

When for a shared variable, multiple threads are reading the same shared variable, the variable value is written to separate memory copy, uncertain time in the future synchronization with the main memory, which will lead to a different thread of variable done modification, and not visible to each other.

The volatile keyword visible shared variables can be achieved.

Fifth, orderliness

Whether understood as a program in accordance with the code written along the execution.

About consider ordering from within threads and multiple threads between two angles.

When the thread of the program appears to be executed in accordance with the code written order, in fact, different jvm program will have different levels of optimization, specific instructions are executed through reordered.

 

When the threads, any code at any time are likely to cross execution. Unless a program to control the use of volatile, synchronized or lock.

In general, the program serial execution must be because the use of synchronization, mutual exclusion, or is purely coincidental.

 

 

Guess you like

Origin www.cnblogs.com/perfumeBear/p/11803504.html